以下代码具有如下作用:
- 只要有鼠标左键点击在窗口上, window.read() 返回事件'Window Click'"
- 右键单击"Go"按钮将从 window.read() 返回事件"Go + Right Click+"。
- 当第二个输入元素[sg.Input(key='-IN2-')]获得焦点时,将从 window.read() 返回事件"-IN2- +FOCUS+"
- 如果按下"Unbind"按钮,则"Go"按钮的右键单击事件绑定将被取消绑定。
import PySimpleGUI as sg
sg.theme('Dark Green 2')
layout = [ [sg.Text('My Window')],
[sg.Input(key='-IN1-')],
[sg.Input(key='-IN2-')],
[sg.Button('Go'), sg.Button('Unbind'),sg.Button('Exit')]
]
window = sg.Window('Window Title', layout, finalize=True)
window.bind("<Button-1>", 'Window Click')#绑定鼠标左键事件到窗口上,检测到鼠标点击窗口事件之后返回字符串'Window Click'
window['Go'].bind("<Button-3>", ' +RIGHT CLICK+')#绑定鼠标右键到go按钮,检测到鼠标右键在go按钮上返回字符串' +RIGHT CLICK+'
window['-IN2-'].bind("<FocusIn>", ' +FOCUS+')#绑定获取焦点事件到第二输入文本框上,如果检测到该事件,那么返回' +FOCUS+'
while True: # Event Loop
event, values = window.read()
print(event, values)
if event in (sg.WIN_CLOSED, 'Exit'):
break
if event == 'Unbind':#如果点击了按钮解绑
window['Go'].unbind('<Button-3>')#将go按钮上的右键事件解绑
window.close()
List of tkinter events: tkinter事件参考表
Event | Description |
Button-1 / ButtonPress-1 / 1 | Left button is pressed over an element. 1 corresponds to the left button, 2 to the middle button, 3 to the right button. Buttons can go up to 5 |
ButtonRelease-1 | Left button is released over an element. |
Double-Button-1 | An element was double clicked. The 'Double' modifier was used. See below for more modifiers. |
B1-Motion | Left button is held and moved around over an element. |
Motion | Mouse pointer is moved over an element |
Enter | Mouse pointer entered the element |
Leave | Mouse pointer left the element |
Key / KeyPress Keypress-a / a | A key was pressed. can be used to bind specific key/s. When using keysyms, 'Key' or 'KeyPress' can be omitted. |
KeyReleased | A key was released. |
FocusIn | Keyboard has focused on element. |
FocusOut | Keyboard switched focus from element. |
Visibility | Some part of the element is seen on screen |
Modifier keys can be put in front of events.
Windows | MacOS |
Control | Command |
Alt | Option |
Shift | |
Double | |
Triple | |
Quadruple |