0

i am reading the width of a label at three different times and only one of them is producing the correct output.. code:

from tkinter import *

def getwidth(string):
    print(string+str(lbl1.winfo_width()))

root = Tk()

lbl1 = Checkbutton(root, text="test text")
lbl1.grid(row=0,rowspan=2)


print("first "+str(lbl1.winfo_width()))
getwidth("second ")

btn = Button(root, text="GO", command=lambda x="third ": getwidth(x))
btn.grid(row=2)

root.mainloop()

How can i read the correct width (69) during the first two outputs without having to rely on the button command? Thanks

current outputs are:

first 1
second 1
third 69
4

1 回答 1

2

好吧,不幸的是,你不能。前两次是在加载窗口之前完成的(这会导致它返回默认值,1因为尚未绘制标签)。第三次是加载窗口(绘制标签)后完成的,因此它返回正确的数字。

您必须记住,在您调用root.mainloop并加载窗口之前,小部件不会放置在屏幕上。当然,它们存在于幕后(否则NameError会抛出 a),但它们尚未出现在屏幕上并占用空间。因此,当您尝试查看它们占用了多少空间时,您会得到默认数量的1.

于 2013-08-27T14:23:08.887 回答