[Tutor] Variable in tkinter?

Peter Otten __peter__ at web.de
Sun Jul 24 13:20:51 EDT 2016

Steven D'Aprano wrote:

> On Sat, Jul 23, 2016 at 01:55:03PM -0400, R. Alan Monroe wrote:
>> > button = tkinter.Button(frame, text='Up', command=click_up)
>> > button = tkinter.Button(frame, text='Down', command=click_down)
>> > when I first looked at it I thought it would not work, thinking that
>> > the second reference to button = would over write the first one.
>> It DOES overwrite it, in this sense:
>> The first button is a thing that exists because Button() generates it.
>> "button" is a word you can now use to refer to that thing.
>> Later on, the second call to Button() generates a new, separate thing.
>> "button" is now a word you can use to refer to the second thing,
>> but *the first thing doesn't cease to exist*.
> Why not? Why isn't the first button not garbage collected?

The answer is of course always the same: because there is another reference.
The hard part is also always the same: how can that reference be found?

Here's a way to do it in this case:

$ cat tksnippet.py
import tkinter

window = tkinter.Tk()

def click_up():

def click_down():

counter = tkinter.StringVar()

frame = tkinter.Frame(window)
button = tkinter.Button(frame, text='Up', command=click_up)

print("button whose reference we are going to overwrite:")
print(repr(button), button)

button = tkinter.Button(frame, text='Down', command=click_down)

label = tkinter.Label(frame, textvariable=counter)
$ python3 -i tksnippet.py 
button whose reference we are going to overwrite:
<tkinter.Button object at 0x7f5412a9ca90> .139999066974024.139999067097744
>>> forgotten_button = 
>>> forgotten_button
<tkinter.Button object at 0x7f5412a9ca90>
>>> forgotten_button["text"]

So it is indeed the up-button rather than a reused memory address.

The above snippet is only for demonstration purposes; if you plan to access 
a widget later-on you should always use the straightforward approach and 
keep a reference around in your own code.

More information about the Tutor mailing list