DCA- DCA- - 1 year ago 61
Python Question

Unexpected label width value

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):

root = Tk()

lbl1 = Checkbutton(root, text="test text")

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

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


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

Answer Source

Well, unfortunately, you can't. The first two times are done before the window is loaded (which causes it to return the default value of 1 since the label isn't drawn yet). The third time is done after the window is loaded (the label is drawn), so it returns the correct number.

You have to remember that, until you call root.mainloop and load the window, the widgets are not placed on the screen. Sure, they exist behind the scenes (otherwise a NameError would be thrown), but they are not on the screen and taking up space yet. Thus, when you try to see how much space they are taking up, you get the default number of 1.