[python]Tkinter中的event

1、事件app

在Tkinter中事件使用<[modifier-]...type[-detail]>格式的字符串描述的。其中type是事件類型,好比鍵盤按下(Key)、鼠標(Motion/Enter/Leave/Relase)等。modifier事件修飾符,最多見的是Alt、Shit組合鍵和Double事件。detail描述哪一個鍵盤按鈕或者鼠標按鈕。less

<Button-1>:鼠標左擊事件函數

<Double-Button-1>:雙擊事件spa

<B2-Motion>:鼠標移動事件code

<ButtonRelease-1>:鼠標釋放事件事件

<Enter>:鼠標進入事件ci

<Leave>:鼠標離開時產生的事件字符串

<BackSpace> <Return> <F5> <Shift_L> <Shift_R>:特殊鍵事件it

<Key>:全部的鍵按鍵事件io

<a> <space> <less> :A、空格、<對應鍵的事件

<Shift-Up> <Control-Alt-a> 組合鍵事件

<Configure>大小改變事件

2、事件處理

事件處理是當事件發生時控件的響應函數。

# 函數

def handle(event):

        pass

# 或者類的一個方法

def handle(self, event):

        pass

event是事件的一個實例,經常使用的屬性有:

.type:事件類型,字符串,即事件字符串中的type。

.char:用於鍵盤事件,表示按下鍵的ascii碼。

.keycode:用於鍵盤事件,表示鍵盤代碼。

.delta:用於描述鼠標滾動事件,表示滾輪滾動的距離。

3、自定義事件

自定義事件字符串,是包含在書名號中,好比<< Complete >>。在自定義事件中,須要用代碼觸發事件,使用self.generate_event('<<Complete>>'

四、事件綁定

事件綁定是當一個事件發生時某個控件可以作出響應。能夠將多個事件綁定到同的組件。

共有三種不一樣層次的綁定方式。

實例綁定bind:綁定在某一個控件上。

類型綁定bind_class:綁定在某一個類型控件上。

應用綁定bind_all:綁定在全部控件上。

# 在instance級別與printEvent綁定

bt1 = Button(root,text = 'instance event')

bt1.bind('<Return>',printEvent)

# 在bt1的Toplevel級別與printToplevel綁定

bt1.winfo_toplevel().bind('<Return>',printToplevel)

# 在class級別綁定事件printClass

root.bind_class('Button','<Return>',printClass)

# 在application all級別綁定printAppAll

bt1.bind_all('<Return>',printAppAll)

#使用protocal綁定

# 使用protocol將WM_DELETE_WINDOW與printProtocol綁定

root.protocol('WM_DELETE_WINDOW',printProtocol)

相關文章
相關標籤/搜索