[Tutor] Variable in tkinter?

Alan Gauld alan.gauld at yahoo.co.uk
Sun Jul 24 15:08:35 EDT 2016


On 23/07/16 16:38, Jim Byrnes wrote:

> # the views
> frame = tkinter.Frame(window)
> frame.pack()
> button = tkinter.Button(frame, text='Up', command=click_up)
> button.pack()
> button = tkinter.Button(frame, text='Down', command=click_down)
> button.pack()

> that is wrong because the program does work.  Could someone explain to 
> me why it works?

Others have pointed out that a hidden reference to the buttons exists.
In fact Tkinter, in common with most GUIIs, works by building a tree of
objects starting at the top level window and then working down thru'
each lower level.

Usuially in Tkinter we start with  a line like

top = tkinter.Tk()   # create the topmost widget

Then when we create subwidgets, like your frame we
pass the outer widget as the parent:

frame = tkinter.Frame(top)

Then when you create the buttons you pass frame
as the first argument which makes frame the parent
of the buttons.

What happens is that when you create the widget the
parent object adds your new instance to its list of
child widgets. And that's the hidden reference that keeps
your button alive even after you overwrite the button
variable.

You can access the widget tree of any widget using
its 'children' attribute:


>>> import tkinter as tk
>>> top = tk.Tk()
>>> f = tk.Frame(top)
>>> f.pack()
>>> tk.Label(f,text="Hello there!").pack()
>>> f.children
{'140411123026128': <tkinter.Label object at 0x7fb4031c48d0>}
>>>

But it's not very user friendly so if you need to access
a widget after creating it its better to use a unique
variable to store a reference.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list