python - Why is Button parameter “command” executed when declared? -
my code is:
from tkinter import * admin = tk() def button(an): print print 'het' b = button(admin, text='as', command=button('hey')) b.pack() mainloop()
the button doesn't work, prints 'hey' , 'het' once without command, , then, when press button nothing happens.
the command
option takes reference function, fancy way of saying need pass name of function. when button('hey')
calling function button
, and result of being given command
option.
to pass reference must use name only, without using parenthesis or arguments. example:
b = button(... command = button)
if want pass parameter such "hey" must use little code:
- you can create intermediate function can called without argument , calls
button
function, - you can use
lambda
create referred anonymous function. in every way it's function except doesn't have name. when calllambda
command returns reference created function, means can used value ofcommand
option button. - you can use functools.partial
for me, lambda
simplest since doesn't require additional imports functools.partial
does, though people think functools.partial
easier understand.
to create lambda function calls button
function argument this:
lambda: button('hey')
you end function functionally equivalent to:
def some_name(): button('hey')
as said earlier, lambda
returns reference nameless function. since reference command
option expects can use lambda
direction in creation of button:
b = button(... command = lambda: button('hey'))
there's question on site has lot of interesting comments lambda, in general. see question why python lambdas useful?. same discussion has an answer shows how use lambdas in loop when need pass in variable callback.
finally, see section titled tkinter callbacks on effbot.org nice tutorial. coverage of lambda pretty lean information there might still useful.
Comments
Post a Comment