python Tkinter事件绑定,参数传递

转载

原文地址:https://blog.csdn.net/weixin_38428980/article/details/81225731

一般情况下,事件处理都是下面这样的

#coding=utf-8
 
import Tkinter
 
def handler():
    '''事件处理函数'''
    print "handler"
 
 
if __name__=='__main__':
    root = Tkinter.Tk()
    # 通过中介函数handlerAdapotor进行command设置
    btn = Tkinter.Button(text=u'按钮', command=handler)
    btn.pack()
    root.mainloop()

但如果handler()函数需要参数该怎么办呢,很简单,使用lambda

#coding=utf-8
 
import Tkinter
 
def handler(a, b, c):
    '''事件处理函数'''
    print "handler", a, b, c
 
 
if __name__=='__main__':
    root = Tkinter.Tk()
    # 通过中介函数handlerAdapotor进行command设置
    btn = Tkinter.Button(text=u'按钮', command=lambda : handler(a=1, b=2, c=3))
    btn.pack()
    root.mainloop()

但对于想使用event的情况,像btn.bind("<Button-1>", handler),又该怎么办呢,如下:

#coding=utf-8
 
import Tkinter
 
def handler(event, a, b, c):
    '''事件处理函数'''
    print event
    print "handler", a, b, c
 
 
if __name__=='__main__':
    root = Tkinter.Tk()
    btn = Tkinter.Button(text=u'按钮')
 
    # 通过中介函数handlerAdaptor进行事件绑定
    btn.bind("<Button-1>",lambda event:handle(1, 2, 3))
 
    btn.pack()
    root.mainloop()
 

 

posted @ 2019-04-16 16:54  远洪  阅读(11565)  评论(2编辑  收藏  举报