第五章、事件
1. 事件 event
什么是事件?
事件是用户在操作图形用户界面时发生的动作。如鼠标,键盘等对窗口元素操作,输入框焦点进入、离开等操作。
事件的来源
按键,鼠标,或是定时器,窗口关闭等。
绑定事件
bind(事件类型,事件处理函数)
事件处事函数的定义格式:
def xxxx(event):
pass
注: event为事件类型
常用事件
<Button>
鼠标的全部按键按下<Button-1>
数值可以为1,2,3分别代表左中右三个鼠标键<ButtonRelease>
鼠标的全部按键抬起<ButtonRelease-1>
左键抬起<Key>
或<KeyPress>
全部的键盘按键按下<KeyPress-a>
a键被按下<KeyPress-q>
<KeyPress-space>
<KeyPress-Escape>
Esc键按下<KeyPress-Left>
左方向键按下<KeyPress>
键被按下<KeyRelease>
键被抬起<KeyRelease-a>
a键抬起<Control-v>
Ctrl+v<F1>
F1键按下<ButtonRelease-1>
事件event的属性
事件
说明
widget
产生event的实例
type
事件类型
key event
keycode
键盘的代码(操作系统级别的编码)
keysym
按键的符号名称(字符串)
keysym_num
按键对应的ASCII值
char
按键对应的字符(字符串)
mouse event
x, y
鼠标相对于窗口控件的位置,单位:像素
x_root, y_root
鼠标相对于屏幕左上角的绝对位置,单位:像素
num
按钮的num编号,(仅鼠标事件)
resize event
width, height
widget新大小
事件对象的文档
| num - mouse button pressed (ButtonPress, ButtonRelease)
| focus - whether the window has the focus (Enter, Leave)
| height - height of the exposed window (Configure, Expose)
| width - width of the exposed window (Configure, Expose)
| keycode - keycode of the pressed key (KeyPress, KeyRelease)
| state - state of the event as a number (ButtonPress, ButtonRelease,
| Enter, KeyPress, KeyRelease,
| Leave, Motion)
| state - state as a string (Visibility)
| time - when the event occurred
| x - x-position of the mouse
| y - y-position of the mouse
| x_root - x-position of the mouse on the screen
| (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
| y_root - y-position of the mouse on the screen
| (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
| char - pressed character (KeyPress, KeyRelease)
| send_event - see X/Windows documentation
| keysym - keysym of the event as a string (KeyPress, KeyRelease)
| keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
| type - type of the event as a number
| widget - widget in which the event occurred
| delta - delta of wheel movement (MouseWheel)
按键事件类型
- KeyPress, Key 按键按下
- KeyRelease 按键松开
鼠标事件类型
- ButtonPress, Button 鼠标按键点击
- ButtonRelease 鼠标按键抬起
- Motion 鼠标按键移动
- MouseWheel 鼠标滚轮转动(暂不能用)
Widget事件
- Enter 进入Widget
- Leave 离开Widget(不起作用)
进入Widget和离开Widget
- FocusIn 获取焦点?
- FocusOut 失去焦点?
示例
import tkinter
root = tkinter.Tk()
def mouseDownEvent(e):
print("鼠标左键按下, 在:",
e.x, e.y, e.x_root, e.y_root)
def mouseUPEvent(e):
print("鼠标左键抬起")
def keyDown(e):
print("有按键按下")
def keyUp(e):
print("有按键抬起")
root.bind('<Button-1>', mouseDownEvent)
root.bind('<ButtonRelease-1>', mouseUPEvent)
root.bind('<KeyPress-a>', keyDown)
root.bind('<KeyRelease-a>', keyUp)
root.mainloop()