[Tutor] why can use a widget assigned to a variable or just use it on it's own?

Steven D'Aprano steve at pearwood.info
Mon Jul 2 07:21:04 EDT 2018

On Mon, Jul 02, 2018 at 11:54:08AM +1000, Chris Roy-Smith wrote:
> Hi,
> I'm trying to understand working with objects.
> If I have grasped things correctly a widget is an object.

In Python, all values are objects. (That's not the case in all 

> So why can I 
> assign the widget, or use it stand alone? See sample code below

That depends on the object, but in general, you can use any object you 
like even if it doesn't survive the experience. Python knows enough to 
only access objects which are still alive.

That's *incredibly common* for small, lightweight values like floats and 
strings. We might say:

print(math.sin(1.3*math.pi) + 1)

which creates (and then destroys) the following transient objects:

* the float 1.3

* then the float 4.084070449666731 (multiplying the above by pi)

* then the float -0.8090169943749473 (calling sin on the above)

* then 0.19098300562505266 (adding 1)

none of which survive more than a few microseconds. By the time the 
final value is printed, all of those transient objects will have been 
reclaimed for recycling by the garbage collector, their memory ready for 

The same applies for big, complex objects. But under normal 
circumstances, the bigger and more complex, the more unlikely you are to 
treat it as a transient, disposable object.

(Creating lightweight objects is cheap, but the bigger the object, the 
less cheap it is.)

In the case of tkinter, things are even more murky. Like many (all?) GUI 
frameworks, tkinter does a lot of behind the scenes clever stuff that 
makes it easier to use at the cost of being less comprehensible. And so:

> # as I understand it this will create an instance of the button widget 
> called b1
> b1=Button(main, text='instantce', command= lambda b='goodbye' : 
> print(b)).grid(row=1, column=0)

Actually, no, if you print the value of b1 -- or print its repr, 
print(repr(b1)) -- you might be in for a surprise. Your b1 is not 
actually the button, but the None object.

But don't worry, the button object itself is safely attached to the TK 
main window, as if by magic. (That's tkinter's magic: the first argument 
to the Button constructor is the window to attach it to.)

> # but here I haven't made an instance, but all seems well
> Button(main, text='test1', command=lambda a='hello' 
> :print(a)).grid(row=0, column=0)

Indeed. You don't have to hold onto the button, because the main window 
does it for you.


More information about the Tutor mailing list