Python Tkinter: Attempt to get widget size
Asked Answered
F

2

16

I am trying to find the size of my window by using the winfo_geometry() function but it ends up returning 1x1+0+0 I have also tried winfo_height, winfo_width but i keep getting 1

CODE

from tkinter import *

root=Tk()

root.geometry('400x600')

print (root.winfo_width())
print (root.winfo_height())
print (root.winfo_geometry())

root.mainloop()
Forbear answered 11/11, 2012 at 0:59 Comment(0)
D
29

You are trying to get the dimensions before the window has been rendered.

Add a root.update() before the prints and it shows the correct dimensions.

from Tkinter import *

root=Tk()

root.geometry('400x600')

root.update()

print (root.winfo_width())
print (root.winfo_height())
print (root.winfo_geometry())

root.mainloop()
Dactylogram answered 11/11, 2012 at 1:8 Comment(0)
S
1

The right way to find the actual width within the initial procedure to display a window is to use winfo_reqwidth() and winfo_reqheight(). It shows you the parameter that is requested to tkinters geometry manager. Example:

root = tk.Tk()
print(f'''width is {root.winfo_width()},
requested width is {root.winfo_reqwidth()}''')
root.mainloop()
Spectrometer answered 28/10, 2022 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.