如何在tkinter中将参数传递给事件处理程序?

2024-05-15 16:41:24 发布

您现在位置:Python中文网/ 问答频道 /正文

widget.bind('<Button-1>',callback)   # binding 

def callback(self,event)
    #do something

我需要给callback()传递一个参数。参数是字典对象。


Tags: 对象selfevent参数字典binddefcallback
3条回答

我认为在大多数情况下,回调不需要任何参数,因为回调可以是访问实例成员的实例方法:

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解决方案也很好

那怎么办

import functools
def callback(self, event, param):
    pass
arg = 123
widget.bind("", functools.partial(callback, param=arg))

可以使用^{}定义匿名函数,例如:

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)

相关问题 更多 >