事件(Event)就是程序中发生的事。例如敲击键盘上的某一个键、单击鼠标等。
对于事件,程序需要对其作出反应。
程序可以使用事件处理函数来指定当出发某个事件时所做出的反应。
python中的事件主要有:
1.键盘事件:
KeyPress:按下键盘某键时触发
KeyRelease:释放某个键时触发
2.鼠标事件
ButtonPress/Button:按下鼠标某个键时触发,表示按下左键,表示中键,。
ButtonRelease:释放鼠标某个键时触发
Motion:鼠标拖拽某个组件移动时触发
Enter:鼠标指针进入某个组件时触发
Leave:鼠标指针移出某个组件时触发
MouseWheel:鼠标滚轮滚动时触发
3.窗体事件
Visibility:组件变为可视状态时触发
Configure:组件大小改变时触发
事件类型必须放置于尖括号<>内。
用法例子:
#按下鼠标左键
#按下键盘上的A键
#同时按下Ctrl、Shift、和A键
可以使用bind()函数,将某个事件和某个函数相关联。
实例:
from tkinter import *root=Tk()defprintRect(event):print(‘rectangle左键事件’)defprintRect2(event):print(‘rectangle右键事件’)defprintLine(event):print(‘Line事件’)
cv= Canvas(root, bg=’white’)
rt1= cv.create_rectangle(10, 10, 110, 110, width=8, tags=’r1′) #此长方形标签为r1
cv.tag_bind(‘r1’, ”, printRect) #按标签绑定,左键点击r1时,执行printRect事件
cv.tag_bind(‘r1’, ”, printRect2)
cv.create_line(180, 70, 280, 70, width=10, tags=’r2′)
cv.tag_bind(‘r2’, ”, printLine) #点击r2线条时,执行printLine
cv.pack()
root.mainloop()
事件处理函数:事件处理函数往往带有一个event参数。传递event对象实例。
实例1:
from tkinter import *
defprintkey(event):print(‘你按下了:’ + event.char) #监听了键盘的事件,event.char表示字符
root=Tk()
entry= Entry(root) #实例化输入框
entry.bind(”, printkey) #监听在输入框输入的某键
entry.pack()
root.mainloop()
实例2:
from tkinter import *
defleftClick(event):print(‘x坐标:’, event.x)print(‘y坐标:’, event.y)print(‘相对于屏幕左上角的x坐标:’, event.x_root)print(‘相对于屏幕左上角的y坐标:’, event.y_root)
root=Tk()
lab= Label(root, text=’Hello’)
lab.pack()
lab.bind(”, leftClick) #监听鼠标左键点击位置的坐标
root.mainloop()