第五章、事件

1. 事件 event

什么是事件?

事件是用户在操作图形用户界面时发生的动作。如鼠标,键盘等对窗口元素操作,输入框焦点进入、离开等操作。

事件的来源

按键,鼠标,或是定时器,窗口关闭等。

绑定事件

bind(事件类型事件处理函数)

事件处事函数的定义格式:

def xxxx(event):
    pass

注: event为事件类型

常用事件

事件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)

按键事件类型

鼠标事件类型

Widget事件

进入Widget和离开Widget

示例

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()