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= "你好世界!",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("标签的宽度为:", width, "pixels") win.mainloop()输出结果
运行上面的代码将显示一个包含 Label 小部件的窗口。
当我们编译代码时,它会在控制台上打印标签小部件的宽度。
标签的宽度为: 148 pixels