您好,欢迎来到百家汽车网。
搜索
您的当前位置:首页python学习之pysimplegui特殊键盘事件“enter”响应学习

python学习之pysimplegui特殊键盘事件“enter”响应学习

来源:百家汽车网
python学习之pysimplegui特殊键盘事件“enter”响应学习

  ps:很⾼兴能开通博客和⼤家分享也是记录⾃⼰的学习过程。

  起因:在利⽤pysimplegui进⾏python gui⼩程序开发的时候,遇到⼀些问题,直接将回车事件绑定到按钮事件上怎么做,输⼊完⽂本后按下enter,直接相应某个函数或着按钮。但是在百度搜索时发现的记录⾮常少,没找到。

     2、看官⽅⽂档,直接搜索关键词:先在官⽅⽂档中搜索的关键词:“enter ” “event ”,发现了两个关键参

数:“return_keyboard_event”与“enable_event”.。但在寻找关于keyboard的enter事件时这种特殊事件时,⽂档中就只有⼀⾏⼩字The

ENTER key什么的。其实还有两个可以关键词可以搜索,keyboard,键盘,当时没想到,这个是⼀个关键过渡点,但后⾯还是没有思路。⾯对这种英⽂⽂档最开始的感觉是不想去搜去看,但最后发现还是要靠它,靠翻译插件来看的。

     3、找到关键线索,在官⽅提供的github演⽰项⽬⾥⾯通过检索关键词“keyboard”“enter”来寻找,最后找到了,githubdemoprogram find success

import PySimpleGUI as sg\"\"\"

tkinter and Qt do not \"activate\" buttons by pressing the ENTER key with the button highlighted / in focus This demo will enable the application to click on a button if the button has focus (is highlighted) and the user presses the ENTER key.

NOTE that the SPACE BAR works correctly out of the box with both tkinter and Qt. If a button has focus and you press the space bar, then tkinter and Qt will both consider that a button click. But not so with the ENTER key.

The solution is for your program to read the keyboard presses and act upon those directly. It's trivial logic in the end:

1. Get a key press

2. See if the key is the ENTER key

3. Find the Element that currently has focus

4. Click the Button if the Element with focus is a button \"\"\"

QT_ENTER_KEY1 = 'special 16777220'QT_ENTER_KEY2 = 'special 16777221'layout = [[sg.Text('Test of Enter Key use')], [sg.Input(key='-IN-')],

[sg.Button('Button 1', key='-1-')], [sg.Button('Button 2', key='-2-')], [sg.Button('Button 3', key='-3-')], ]

window = sg.Window('My new window', layout, return_keyboard_events=True)while True: # Event Loop event, values = window.read() if event == sg.WIN_CLOSED: break

if event in ('\\r', QT_ENTER_KEY1, QT_ENTER_KEY2): # Check for ENTER key # go find element with Focus print('you shuru le enter')

elem = window.find_element_with_focus()

if elem is not None and elem.Type == sg.ELEM_TYPE_BUTTON: # if it's a button element, click it elem.Click()

# check for buttons that have been clicked elif event == '-1-':

print('Button 1 clicked') elif event == '-2-':

print('Button 2 clicked') elif event == '-3-':

print('Button 3 clicked')window.close()

  补:写了发布了,才发现,写了blog也不⼀定搜的到

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baijiahaobaidu.com 版权所有 湘ICP备2023023988号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务