I'm using Tkinter for a simple trivia game. There are several buttons, one for each answer, and I'd like to run a checkAnswer function with certain parameters when one is clicked.
If I used something like the following:
self.option1 = Button(frame, text="1842", command=self.checkAnswer(question=3, answer=2))
Then it would run checkAnswer and use what it returned (nothing).
Is there a simple way to store the parameters in the button constructor?
This is exactly what functools.partial()
is designed to do:
>>> import functools
>>> print_with_hello = functools.partial(print, "Hello")
>>> print_with_hello("World")
Hello World
>>> print_with_hello()
Hello
partial()
returns a new function that behaves just as the old one, but with any arguments you passed in filled, so in your case:
import functools
...
self.option1 = Button(frame, text="1842", command=functools.partial(self.checkAnswer, question=3, answer=2))
You could create a higher order function to wrap your checkAnswer
function. This would allow you to return a function that wouldn't require any parameters, and therefore could be used as a callback.
For example:
def makeCheckAnswer(self, **kwargs)
return lambda: self.checkAnswer(**kwargs)
This would make your button initialization:
self.option1 = Button(frame, text="1842", command=self.makeCheckAnswer(question=3, answer=2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With