Your problem is that when you do this:
a = Button(win, text="plant", command=setText("plant"))
it tries to evaluate what to set for the command. So when instantiating the Button
object, it actually calls setText("plant")
. This is wrong, because you don't want to call the setText method yet. Then it takes the return value of this call (which is None
), and sets that to the command of the button. That's why clicking the button does nothing, because there is no command set for it.
If you do as Milan Skála suggested and use a lambda expression instead, then your code will work (assuming you fix the indentation and the parentheses).
Instead of command=setText("plant")
, which actually calls the function, you can set command=lambda:setText("plant")
which specifies something which will call the function later, when you want to call it.
If you don't like lambdas, another (slightly more cumbersome) way would be to define a pair of functions to do what you want:
def set_to_plant():
set_text("plant")
def set_to_animal():
set_text("animal")
and then you can use command=set_to_plant
and command=set_to_animal
- these will evaluate to the corresponding functions, but are definitely not the same as command=set_to_plant()
which would of course evaluate to None
again.