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

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

问题描述

假设我有以下按钮与Tkinter的Python中提出:

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)

该方法动作当我preSS按钮,但如果我想一些参数传递给方法行动<被称为/ code>?

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

我曾尝试用下面的code:

I have tried with the following code:

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

这只是调用方法立即和pressing按钮不起任何作用。

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

推荐答案

我个人preFER使用 lambda表达式在这种情况下,因为国际海事组织它更清晰和更简单也不会强迫你写大量的包装方法,如果你没有在调用的方法控制,但肯定的喜好问题。

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的一个按钮命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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