如何获取 Tkinter 窗口小部件的宽度?
Tkinter 窗口小部件应该出现在 Tkinter 应用程序窗口中。可以使用预定义的属性或函数对所有窗口小部件进行配置和自定义。
为了获取 Tkinter 应用程序中某个窗口小部件的宽度,我们可以使用 winfo_width() 方法。它返回窗口小部件的宽度,稍后可以将其打印为输出。
示例
#Import the required libraries
from tkinter import *
#Create an instance of Tkinter Frame
win = Tk()
#Set the geometry
win.geometry("700x350")
#Set the default color of the window
win.config(bg='#aad5df')
#Create a Label to display the text
label=Label(win, text= "Hello World!",font= ('Helvetica 18 bold'), background= 'white', foreground='purple1')
label.pack(pady = 50)
win.update()
#Return and print the width of label widget
width = label.winfo_width()
print("The width of the label is:", width, "pixels")
win.mainloop()输出
运行以上代码将显示一个包含 Label 窗口小部件的窗口。

当我们编译代码时,它将在控制台上打印标签窗口小部件的宽度。
The width of the label is: 148 pixels
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP