Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Store function with parameters

Tags:

python

tkinter

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?

like image 224
Cheezey Avatar asked Dec 04 '22 03:12

Cheezey


2 Answers

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))
like image 54
Gareth Latty Avatar answered Jan 05 '23 11:01

Gareth Latty


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))
like image 34
jtmoulia Avatar answered Jan 05 '23 11:01

jtmoulia