如何将parameter passing给tkinter中的事件处理程序?
widget.bind('<Button-1>',callback) # binding def callback(self,event) #do something
我需要传递一个参数给callback()
。 参数是一个字典对象。
你可以使用lambda
定义一个匿名函数,比如:
data={"one": 1, "two": 2} widget.bind("<ButtonPress-1>", lambda event, arg=data: self.on_mouse_down(event, arg))
请注意,传入的arg
成为您正常使用的参数,就像所有其他参数一样:
def on_mouse_down(self, event, arg): print(arg)
关于什么
import functools def callback(self, event, param): pass arg = 123 widget.bind("", functools.partial(callback, param=arg))
我认为在大多数情况下,你不需要任何callback参数,因为callback可以是一个实例方法,它可以访问实例成员:
from Tkinter import * class MyObj: def __init__(self, arg): self.arg = arg def callback(self, event): print self.arg obj = MyObj('I am Obj') root = Tk() btn=Button(root, text="Click") btn.bind('<Button-1>', obj.callback) btn.pack() root.mainloop()
但是我认为Philipp提出的functools解决scheme也非常好
将callback函数传递给实例并从实例方法调用它。
from tkinter import * class MyClass: def __init__(self, my_callback, message): self.my_callback = my_callback self.message = message def callback(self, event): self.my_callback(self) def my_callback(o): print(o.message) obj = MyClass(my_callback, "I am instance of MyClass") root = Tk() btn=Button(root, text="Click") btn.bind('<Button-1>', obj.callback) btn.pack()
以下是我认为最简单,最易于阅读的解决scheme:
widget.bind('<Button-1>', callback2) def callback(self, event, custom_arg=None): #change "None" to whatever you want the default value to be #do something def callback2(self, event): callback(event, custom_arg=something_you_set) #set custom_arg to whatever you want it to be when Button-1 is pressed
你也可以为一个小部件的callback函数提供参数,只要这个小部件被定义为一个类定义的一部分,也就是说,考虑这个小的python 2.7程序(没有负责程序执行的部分):
import Tkinter as tk #To be able to get "tk.Button" safely from Tkinter import * class EXAMPLE(Frame): def __init__(self,master=None): Frame.__init__(self,master) #make the widgets appear to a grid of size = 2 X 2 for row in range(2): self.grid_rowconfigure(row,minsize=20) for col in range(2): self.grid_columnconfigure(col,minsize=20) #Call our METHOD OF INTEREST self.AnyMethod() #This is our method of interest def AnyMethod(self): #arguments to be supplied self.arg1 = 'I am 1st argument' self.arg2 = 'I am 2nd argument' self.arg3 = 'I am 3rd argument' #Draw the widget, & supply its callback method self.widgetname=tk.Button(self.master,text="My Button",command=self.method_callback) self.widgetname.grid(row=0,column=0) #create a so-called 'shell method' to swallow the REAL callback function def method_callback(self): func_callback(self.arg1,self.arg2,self.arg3) #Define the REAL callback function in the Module's scope def func_callback(arg1,arg2,arg3): print arg1 print arg2 print arg3
注意提供的参数必须self.