Python Tkinter 事件

基本用法

创建按钮时,可通过 command 参数指定 【点击事件函数】,点击按钮时,会调用该 【事件函数】

如下:

button = tk.Button(win, text="点击我", command=on_click)

例子

import tkinter as tk

def on_click():
    print("按钮被点击")

# 创建窗口
win = tk.Tk()
# 窗口标题
win.title("测试")
# 600宽、400高
win.geometry("600x400")

# 添加按钮,并绑定点击事件,点击按钮时执行 on_click() 函数
button = tk.Button(win, text="点击我", command=on_click)
button.pack()

win.mainloop()

进阶用法-鼠标事件

事件格式 事件解释
<Button-1> 鼠标点击(1-左键,2-中键,3-右键)
<Double-Button-1> 鼠标双击(1-左键,2-中键,3-右键)
<B1-Motion> 鼠标拖动(1-左键,2-中键,3-右键)
<ButtonRelease-1> 鼠标按下之后释放(1-左键,2-中键,3-右键)
<Enter> 鼠标进入控件范围(widget),不是键盘按键
<Leave> 鼠标离开控件范围(widget)
import tkinter as tk

def on_click(event):
    print("按钮被点击,event:",event)

# 创建窗口
win = tk.Tk()
# 窗口标题
win.title("测试")
# 600宽、400高
win.geometry("600x400")

# 添加按钮
button = tk.Button(win, text="点击我")

# 绑定事件,点击鼠标左键时执行 on_click() 函数
# 注意:此时事件函数必须有一个参数,否则报错
button.bind('<Button-1>',on_click)
button.pack()

win.mainloop()

事件对象

属性 属性说明 适用事件类型
.char 如果按键事件产生通用ASCII字符,这个字符将赋值给event.char。(特殊ASCII字符,如delete等不属于该属性) <KeyPress>、<KeyRelease> 等按键事件
.keysym 如果按键事件产生特殊ASCII字符,这个字符将赋值给event.keysym。 <KeyPress>、<KeyRelease>等按键事件
.x 鼠标当前位置横坐标,相对于组件左上角
.y 鼠标当前位置纵坐标,相对于组件左上角
.x_root 鼠标当前位置横坐标,相对于屏幕左上角
.y_root 鼠标当前位置纵坐标,相对于屏幕左上角
.width 组件大小发生改变后的宽度
.height 组件大小发生改变后的高度
.type 事件类型 ALL

进阶用法-键盘事件

对应键盘按键:

<Return>
<Cancel>
<BackSpace>
<Tab>
<Shift_L>
<Control_L>
<Alt_L>
<Home>
<Left>
<Up>
<Down>
<Right>
<Delete>
<F1>
<F2>

参考:

https://blog.csdn.net/xiaozhimonica/article/details/87873048


原文出处:/show_1IX65UUfwEcg.html