Python - 存储带参数的函数 [英] Python - Store function with parameters
问题描述
我将 Tkinter 用于一个简单的琐事游戏.有几个按钮,每个答案一个,我想在点击一个时运行带有特定参数的 checkAnswer 函数.
如果我使用以下内容:
self.option1 = Button(frame, text="1842", command=self.checkAnswer(question=3, answer=2))
然后它会运行 checkAnswer 并使用它返回的内容(什么都没有).
是否有一种简单的方法可以将参数存储在按钮构造函数中?
这正是 functools.partial()
旨在:
partial()
返回一个新函数,它的行为与旧函数一样,但填充了您传入的任何参数,因此在您的情况下:
import functools...self.option1 = Button(frame, text="1842", command=functools.partial(self.checkAnswer, question=3, answer=2))
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))
这篇关于Python - 存储带参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!