我正在使用Tkinter进行简单的琐事游戏.有几个按钮,每个答案一个,我想在单击一个时运行带有某些参数的checkAnswer功能.
如果我使用以下内容:
self.option1 = Button(frame, text="1842", command=self.checkAnswer(question=3, answer=2))
Run Code Online (Sandbox Code Playgroud)
然后它将运行checkAnswer并使用它返回的内容(没有).
有没有一种简单的方法来存储按钮构造函数中的参数?
Gar*_*tty 11
这正是functools.partial()设计目的:
>>> import functools
>>> print_with_hello = functools.partial(print, "Hello")
>>> print_with_hello("World")
Hello World
>>> print_with_hello()
Hello
Run Code Online (Sandbox Code Playgroud)
partial() 返回一个新函数,其行为与旧函数一样,但是您传入的任何参数都已填充,因此在您的情况下:
import functools
...
self.option1 = Button(frame, text="1842", command=functools.partial(self.checkAnswer, question=3, answer=2))
Run Code Online (Sandbox Code Playgroud)