tkinter学习-- 九、三种事件绑定方式总结

多种事件绑定方式汇总

组件对象的绑定

1. 通过 command 属性绑定(适合简单不需获取 event 对象)
  Button(root,text=”登录”,command=login)
2. 通过 bind()方法绑定(适合需要获取 event 对象)
  c1 = Canvas(); c1.bind(“<Button-1>”,drawLine) ·

组件类的绑定
  调用对象的 bind_class 函数,将该组件类所有的组件绑定事件:
  w.bind_class(“Widget”,”event”,eventhanler)

from tkinter import  *
root=Tk()
root.geometry("270x30")

def mouseTest1(event):
    print("bind()方法绑定,可以获取event对象")
    print(event.widget)

def mouseTest2(a,b):
    print('a={0},b={1}'.format(a,b))
    print('command方式绑定,不能直接获取event对象')


def mouseTest3(event):
    print('右键单击事件,绑定给所有按钮啦!!')
    print(event.widget)

b1=Button(root,text='测试bind绑定')

b1.pack(side=LEFT)
b1.bind("<Button-1>",mouseTest1)

# command 属性直接绑定事件
b2=Button(root,text='测试command绑定',command=lambda :mouseTest2(2,3))
b2.pack(side=LEFT)

# 给所有 Button 按钮都绑定右键单击事件<Button-2>
b1.bind_class("Button","<Button-3>",mouseTest3) #注意这里的Button加上双引号 这里b1,b2,root皆可

root.mainloop()

 

 

原文地址:https://www.cnblogs.com/yescarf/p/13903550.html