如何将参数传递给 Tkinter 中的 Button 命令? [英] How to pass arguments to a Button command in Tkinter?

查看:37
本文介绍了如何将参数传递给 Tkinter 中的 Button 命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Python 中使用 Tkinter 制作了以下 Button:

Suppose I have the following Button made with Tkinter in Python:

import Tkinter as Tk
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=1, column=1)
button = Tk.Button(master=frame, text='press', command=action)

当我按下按钮时会调用方法 action,但是如果我想向方法 action 传递一些参数怎么办?

The method action is called when I press the button, but what if I wanted to pass some arguments to the method action?

我已尝试使用以下代码:

I have tried with the following code:

button = Tk.Button(master=frame, text='press', command=action(someNumber))

这只是立即调用方法,按下按钮什么也不做.

This just invokes the method immediately, and pressing the button does nothing.

推荐答案

我个人更喜欢在这种情况下使用 lambdas,因为 imo 更清晰、更简单,也不会强迫您编写如果您无法控制被调用的方法,则有很多包装方法,但这当然是一个品味问题.

I personally prefer to use lambdas in such a scenario, because imo it's clearer and simpler and also doesn't force you to write lots of wrapper methods if you don't have control over the called method, but that's certainly a matter of taste.

这就是您使用 lambda 的方式(请注意,函数模块中也有一些柯里化的实现,因此您也可以使用它):

That's how you'd do it with a lambda (note there's also some implementation of currying in the functional module, so you can use that too):

button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))

这篇关于如何将参数传递给 Tkinter 中的 Button 命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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