tkinter 提供了一個(gè)強(qiáng)大的事件驅(qū)動(dòng)機(jī)制:
widget.bind(event, hander)
其中 hander 是可回調(diào)的函數(shù)等句柄。
本章以幾個(gè)例子來說明事件驅(qū)動(dòng)。先載入可能使用到的包:
from tkinter import ttk, Tk
from tkinter import N, W, E, S
from tkinter import StringVar
1 鼠標(biāo)按鍵
下面的代碼提供了一個(gè)綁定鼠標(biāo)左鍵的例子:
class App(Tk):
def __init__(self):
super().__init__()
self.out_var = StringVar()
self.geometry('200x200')
self.text = ttk.Label(textvariable=self.out_var)
self.text.grid()
# 綁定鼠標(biāo)左鍵
self.bind('<1>', self.get_location)
def get_location(self, event):
self.out_var.set(f'點(diǎn)擊的位置: {(event.x, event.y)}')
app = App()
app.mainloop()
該例子通過鼠標(biāo)左鍵獲取窗口的坐標(biāo)位置。顯示效果圖:

圖1 鼠標(biāo)左鍵獲取坐標(biāo)
2 鍵盤按鍵
使用 <Key> 可以獲取鍵盤的按鍵:
class App(Tk):
def __init__(self):
super().__init__()
self.out_var = StringVar()
self.geometry('200x200')
self.text = ttk.Label(textvariable=self.out_var)
# 綁定鼠標(biāo)左鍵
self.bind('<Key>', self.get_char)
self.text.grid()
def get_char(self, event):
self.out_var.set(f'點(diǎn)擊的鍵盤字符為: {(event.char)}')
app = App()
app.mainloop()
效果圖為:

圖2 獲取鍵盤的按鍵
3 獲取鼠標(biāo)移動(dòng)的位置
使用 <Motion> 可以獲取鼠標(biāo)的移動(dòng)位置:
class App(Tk):
def __init__(self):
super().__init__()
self.out_var = StringVar()
self.geometry('200x100')
self.text = ttk.Label(textvariable=self.out_var)
# 綁定鼠標(biāo)左鍵
self.bind('<Motion>', self.stroke)
self.text.grid()
def stroke(self, event):
self.out_var.set(f'當(dāng)前的位置為: {(event.x, event.y)}')
app = App()
app.mainloop()
效果圖:

圖3 捕獲鼠標(biāo)當(dāng)前位置