组件对象的绑定
1、 通过 command 属性绑定(适合简单不需获取 event 对象)
Button(root,text="登录",command=login)
2、 通过 bind()方法绑定(适合需要获取 event 对象)
c1 = Canvas()
c1.bind("<Button-1>",drawLine)
组件类的绑定
3、调用对象的 bind_class 函数,将该组件类所有的组件绑定事件:
w.bind_class("Widget","event",eventhanler)
#coding=utf-8
from tkinter import *
root=Tk()
root.title("三种绑定方式的使用")
root.geometry("300x50")
def mouseTest1(event):
print("bind方式绑定,可以获取event事件对象")
print(event.widget)
def mouseTest2(a,b):
print("command方式绑定,不能直接获取event事件对象")
print("{0}-{1}".format(a,b))
def mouseTest3(event):
print("右键单击事件,绑定给所有按钮")
print(event.widget)
#bind()方式绑定特定事件
b1=Button(root,text="button1")
b1.bind("<Button-1>",mouseTest1)
b1.pack(side="left")
#command属性直接绑定事件
b2=Button(root,text="button2",command=lambda :mouseTest2("Vince","Jenny"))
b2.pack(side="left")
#bind_class()方式绑定事件给所有同一类的组件,即给所有按钮绑定右键单击
#也是可以是b2.bind_class()
b1.bind_class("Button","<Button-3>",mouseTest3)
root.mainloop()

三种绑定事件方式.png
网友评论