winfo_width() returns 1 even after using pack()

2019-06-24 16:38发布

问题:

I have searched online and I have tried solving it on my own but I have not been able to solve it. Even after rendering the widget the winfo functions are returning wrong height and width

from tkinter import *

root = Tk()

frame = Frame(root)

label1 = Label(frame, text = "hello")
label1.pack()

label2 = Label(frame, text = "hello")
label2.pack()

label3 = Label(frame, text = "hello")
label3.pack()

frame.pack()    
print(frame.winfo_width(),frame.winfo_height())

#prints "1 1"

root.mainloop()

回答1:

You need to update_idletasks:

Calls all pending idle tasks, without processing any other events. This can be used to carry out geometry management and redraw widgets if necessary, without calling any callbacks.

frame.pack()
root.update_idletasks() 
print(frame.winfo_width(), frame.winfo_height())