[Tutor] Variable in tkinter?

Jim Byrnes jf_byrnes at comcast.net
Sun Jul 24 15:27:06 EDT 2016


On 07/24/2016 02:08 PM, Alan Gauld via Tutor wrote:
> 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.
>

Thanks Peter and Alan,

After I proved to myself that it worked and I thought about it, I 
suspected it had to do with a reference.  It's nice to have it confirmed 
is such a clear manner.

Regards,  Jim



More information about the Tutor mailing list