Python - Store function with parameters

python, tkinter

Solution

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))

Problem

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?

Original source