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


  ps:很高兴能开通博客和大家分享也是记录自己的学习过程。

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

 

  过程:1、先在baidu上搜索的关键词:pysimplegui  enter   event   找不到,花了很多时间,低效。找到一篇关于在python返回键盘事件的文章:https://www.cnblogs.com/xia-weiwen/p/13512463.html,没什么用

     2、看官方文档,直接搜索关键词:先在官方文档中搜索的关键词:“enter  ”  “event ”,发现了两个关键参数:“return_keyboard_event”与“enable_event”.。但在寻找关于keyboard的enter事件时这种特殊事件时,文档中就只有一行小字The ENTER key什么的。其实还有两个可以关键词可以搜索,keyboard,键盘,当时没想到,这个是一个关键过渡点,但后面还是没有思路。面对这种英文文档最开始的感觉是不想去搜去看,但最后发现还是要靠它,靠翻译插件来看的。

     3、找到关键线索,在官方提供的github演示项目里面通过检索关键词“keyboard”“enter”来寻找,最后找到了,github demoprogram find success

 

  结论:if event == ‘\r’    。还有两个在代码中贴出。网址是https://github.com/PySimpleGUI/PySimpleGUI/blob/master/DemoPrograms/Demo_Keyboard_ENTER_Presses_Button.py

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也不一定搜的到  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM