Python中GUI设计之tkinter控件的使用(事件与绑定)

1. 事件绑定 bind(event,handler)

除了前面提到的Button中绑定command的事件之外,还有一种使用bind进行绑定事件的方式

介绍几个常用的鼠标事件:

< Button-1> 单击鼠标左键
< Button-3> 单击鼠标右键
< Button-4> 鼠标滚轮向上滚动
< Button-5> 鼠标滚轮上下滚动
< Motion> 鼠标移动-
< ButtonRelease-1> 松开鼠标左键
< DoubleButton-1> 双击鼠标左键

2. 上代码

from tkinter import*


def showGrilFriend():
    lbl.config(text="我的名字叫女朋友")


root=Tk()
root.title("Print GrilFriend")
root.geometry("300x200")

# 按钮
btn=Button(root,text="打印",command=showGrilFriend)
btn.pack(anchor=S)

# 创建一个显示用的Label
lbl=Label(root,bg="yellow",fg="blue",height=2,width=15,font="Times 16 bold")
lbl.pack()

root.mainloop()

下面使用bind方法为Button绑定事件
唯一的区别就是不在需要绑定command,并且回调中需要传事件对象作为参数

from tkinter import*

# 回调的时候,传入event事件对象
def showGrilFriend(event):
    lbl.config(text="我的名字叫女朋友")


root=Tk()
root.title("Print GrilFriend")
root.geometry("300x200")

# 按钮
btn=Button(root,text="打印")
btn.pack(anchor=S)
# 将按钮的单击事件绑定到showGrilFriend回调函数上
btn.bind("<Button-1>",showGrilFriend) 

# 创建一个显示用的Label
lbl=Label(root,bg="yellow",fg="blue",height=2,width=15,font="Times 16 bold")
lbl.pack()

root.mainloop()

运行:
在这里插入图片描述

上代码:实时打印鼠标的位置

from tkinter import*

# 打印鼠标位置
def printMouseLocation(event):
    x=event.x
    y=event.y
    printInfo="鼠标位置  x:{},y:{}".format(x,y)
    var.set(printInfo)
    
root=Tk()
root.title("Print mouse location")
root.geometry("500x300")

x,y=0,0
var=StringVar()
text="鼠标位置  x:{},y:{}".format(x,y)
var.set(text) # 显示的初始位置为0,0

lbl=Label(root,textvariable=var)
lbl.pack(anchor=S,side=RIGHT,padx=10,pady=10)

# 为鼠标的移动事件绑定printMouseLocation方法
root.bind("<Motion>",printMouseLocation)
root.mainloop()

运行:
在这里插入图片描述

3. 取消事件绑定 unbind(event)

from tkinter import*

def callback(event):
    print("鼠标点击位置:",event.x,event.y)

# 取消事件订阅
def cancelEvent():
    frame.unbind("<Button-1>") # 取消绑定
    print("鼠标位置打印功能已经被取消")
    
root=Tk()
root.title("Mouse location")

btn=Button(root,text="取消事件",fg="black",command=cancelEvent)
btn.pack(side=TOP,padx=5,pady=5)

frame=Frame(root,width=500,height=280,bg="yellow")
frame.bind("<Button-1>",callback)
frame.pack()

root.mainloop()

运行:
在这里插入图片描述

4. 多事件绑定

from tkinter import*
 
# 单击事件回调
def clickCallback(event):
    print("this is click event")
# 单击并松开事件回调
def releaseCallback(event):
    print("this is release event")
    
root=Tk()
root.title("Multi event")
root.geometry("300x100")

btn=Button(root,text="Trigger")
btn.pack(anchor=W,padx=10,pady=10)
btn.bind("<Button-1>",clickCallback,add="+") # 绑定单击事件
btn.bind("<ButtonRelease-1>",releaseCallback,add="+") # 绑定松手事件

root.mainloop()

运行
在这里插入图片描述
当然,除了以上介绍的鼠标事件,键盘也是有事件的,大同小异,这里就不做介绍了
拜了个拜,如有疑问欢迎随时交流。。。。

猜你喜欢

转载自blog.csdn.net/qq_34699535/article/details/120393509
今日推荐