Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Retrieve ttk.Frame size

Tags:

python

tkinter

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()
like image 973
guyd Avatar asked Apr 20 '26 19:04

guyd


2 Answers

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()
like image 74
Right leg Avatar answered Apr 23 '26 09:04

Right leg


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)
like image 38
patthoyts Avatar answered Apr 23 '26 09:04

patthoyts