pysimplegui绑定tkinter事件

这篇博客探讨了如何使用PySimpleGUI绑定Tkinter事件,如鼠标左键点击、右键单击按钮和输入框焦点变化。通过示例代码展示了如何监听和响应特定事件,包括解除事件绑定的操作。此外,还提到了Tkinter的事件参考表和修饰键的应用。
摘要由CSDN通过智能技术生成

以下代码具有如下作用:


  1. 只要有鼠标左键点击在窗口上, window.read() 返回事件'Window Click'"‎
  2. ‎右键单击"Go"按钮将从 window.read() 返回事件"Go + Right Click+"。‎
  3. ‎当第二个输入元素[sg.Input(key='-IN2-')]获得焦点时,将从 window.read() 返回事件"-IN2- +FOCUS+"‎
  4. ‎如果按下"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.

Keysyms

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值