Python - 存储带参数的函数 [英] Python - Store function with parameters

查看:48
本文介绍了Python - 存储带参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Tkinter 用于一个简单的琐事游戏.有几个按钮,每个答案一个,我想在点击一个时运行带有特定参数的 checkAnswer 函数.

如果我使用以下内容:

self.option1 = Button(frame, text="1842", command=self.checkAnswer(question=3, answer=2))

然后它会运行 checkAnswer 并使用它返回的内容(什么都没有).

是否有一种简单的方法可以将参数存储在按钮构造函数中?

解决方案

这正是 functools.partial() 旨在:

<预><代码>>>>导入功能工具>>>print_with_hello = functools.partial(打印,你好")>>>print_with_hello("世界")你好,世界>>>print_with_hello()你好

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆