假设我在Python中使用Tkinter创建了以下按钮:

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)

当我按下按钮时,方法操作被调用,但是如果我想将一些参数传递给方法操作呢?

我尝试了以下代码:

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

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


关于解决这个问题的标准技术(不是特定于tkinter的),请参阅Python参数绑定。在Tkinter(或其他GUI框架)中使用回调有一些特殊的考虑,因为回调的返回值是无用的。

如果您尝试在一个循环中创建多个button,并根据循环计数器向每个button传递不同的参数,则可能会因为所谓的延迟绑定而遇到问题。详情请参阅tkinter在for循环中创建按钮传递命令参数。


当前回答

为了让Nae的回答更详细一点,这里有一个完整的例子,其中包括向每个按钮包含不同值的回调传递变量的可能性:

import tkinter as tk
    
def callback(text):
    print(text)

top = tk.Tk()
Texts=["text1", "text2", "text3"]
Buttons=[]

for i, z in enumerate(Texts):
    Buttons.append(tk.Button(top, text=z, command= lambda ztemp=z : callback(ztemp)))
    Buttons[i].pack(side=tk.LEFT, padx=5)

top.mainloop()

通过定义临时变量ztemp,该变量的值在定义按钮时得到固定。

其他回答

基于Matt thompson的回答:一个类可以被设置为可调用的,这样它就可以代替函数使用:

import tkinter as tk

class Callback:
    def __init__(self, func, *args, **kwargs):
        self.func = func
        self.args = args
        self.kwargs = kwargs
    def __call__(self):
        self.func(*self.args, **self.kwargs)

def default_callback(t):
    print("Button '{}' pressed.".format(t))

root = tk.Tk()

buttons = ["A", "B", "C"]

for i, b in enumerate(buttons):
    tk.Button(root, text=b, command=Callback(default_callback, b)).grid(row=i, column=0)

tk.mainloop()

我个人更喜欢在这种情况下使用lambdas,因为在我看来,它更清晰、更简单,而且如果您无法控制被调用的方法,也不会强迫您编写大量的包装器方法,但这当然是个人喜好的问题。

这就是你使用lambda的方式(注意,在函数模块中也有一些curry的实现,所以你也可以使用它):

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

为了让Nae的回答更详细一点,这里有一个完整的例子,其中包括向每个按钮包含不同值的回调传递变量的可能性:

import tkinter as tk
    
def callback(text):
    print(text)

top = tk.Tk()
Texts=["text1", "text2", "text3"]
Buttons=[]

for i, z in enumerate(Texts):
    Buttons.append(tk.Button(top, text=z, command= lambda ztemp=z : callback(ztemp)))
    Buttons[i].pack(side=tk.LEFT, padx=5)

top.mainloop()

通过定义临时变量ztemp,该变量的值在定义按钮时得到固定。

我迟到了,但有一个很简单的方法。

import tkinter as tk
def function1(param1, param2):
    print(str(param1) + str(param2))

var1 = "Hello "
var2 = "World!"
def function2():
    function1(var1, var2)

root = tk.Tk()

myButton = tk.Button(root, text="Button", command=function2)
root.mainloop()

您只需将想要使用的函数包装到另一个函数中,并在按下按钮时调用第二个函数。

Python为函数参数提供默认值的能力为我们提供了一条出路。

def fce(x=myX, y=myY):
    myFunction(x,y)
button = Tk.Button(mainWin, text='press', command=fce)

参见:https://tkdocs.com/shipman/extra-args.html

对于更多的按钮,你可以创建一个函数,返回一个函数:

def fce(myX, myY):
    def wrapper(x=myX, y=myY):
        pass
        pass
        pass
        return x+y
    return wrapper

button1 = Tk.Button(mainWin, text='press 1', command=fce(1,2))
button2 = Tk.Button(mainWin, text='press 2', command=fce(3,4))
button3 = Tk.Button(mainWin, text='press 3', command=fce(9,8))