I'm tring to get Frame's size - but no luck.
in code below- I got both answers ,"0" ( line marked with ***)
from tkinter import *
from tkinter import ttk
root = Tk()
w = '400'
h = '100'
root.geometry('{}x{}'.format(w, h))
root.configure(bg='lightgreen')
txt = StringVar()
txt.set("Hello")
testframe = ttk.Frame(root)
testframe.grid(row=0, column=1 )
label1 = ttk.Label(testframe, textvariable=txt)
label1.grid(row=0, column=0)
print(testframe["width"], testframe.cget("width")) ***This line
root.mainloop()
The update method needs to be called first, so as to have the widget rendered.
If it is not, then its width is equal to zero.
This is explained in this answer.
Now, the problem with testframe['width'] is that it's only a hint of the actual width of the widget, as explained in this answer.
The following code will ouput 32, as expected.
from tkinter import *
from tkinter import ttk
root = Tk()
w = '400'
h = '100'
root.geometry('{}x{}'.format(w, h))
root.configure(bg='lightgreen')
txt = StringVar()
txt.set("Hello")
testframe = ttk.Frame(root)
testframe.grid(row=0, column=1 )
label1 = ttk.Label(testframe, textvariable=txt)
label1.grid(row=0, column=0)
# Modified lines
testframe.update()
print(testframe.winfo_width())
root.mainloop()
The frame widget will not have a size until it gets mapped on screen. There is a Tk event raised when a widget is mapped so the right solution for this example is to bind the <Map> event for the frame and do the print statement in the event handler function.
def on_frame_mapped(ev):
print(ev.widget.winfo_width())
testframe.bind('<Map>', on_frame_mapped)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With