tags:

views:

632

answers:

1

I was trying to write code that would auto-close a Toplevel Tk window in Python.

I ended up getting it to work, but ran into a little problem along the way that I wasn't able to figure out.

The second two buttons work, but the first one doesn't and I don't understand why...

Any ideas?

from Tkinter import *

root = Tk()
def doDestroy ():
    TL.destroy()

TL = Toplevel()
TL.b = Button (TL, text="lambda destroy", command=lambda: TL.destroy)
TL.b.pack()

TL.b2 = Button (TL, text="callback destroy", command=doDestroy)
TL.b2.pack()

de = lambda: TL.destroy()
TL.b3 = Button (TL, text="lambda that works", command=de)
TL.b3.pack()
root.mainloop()
+5  A: 

Because it returns a function and not its result.

You should put:

command=TL.destroy

or if you used lambda:

command=lambda: TL.destroy()
Piotr Lesnicki
I understand that lambda returns a function, but isn't that the same as passing TL.destroy? Both are references to functions, right?
Hortitude
no, lambda works exactly like def but it's anonymous, you have to put the same thing in the body. So in your try with lambda, command is not assigned a function, but a function returning a function (one indirection too much). Whereas TL.destroy is a function, so it's OK.
Piotr Lesnicki
Got it. Thanks!
Hortitude