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