Python PySimpleGUI:如何等待条件满足且不冻结GUI?
Python GUI操控实验室设备的等待问题及后续疑问
我正在学习用Python制作GUI,目标是用其操控实验室设备,目前遇到了让GUI等待条件满足的问题。
最初尝试使用如下while循环(实际代码中会定期向测量设备发送查询,例如判断是否完成测量):
while i < some_limit: time.sleep(1) print(i) i+=1
查阅资料后发现time.sleep()会导致GUI冻结,解决方法之一是使用线程,于是编写了如下示例代码:
import threading import time import PySimpleGUI as sg def side_thread(limit): i=0 while i<=limit: time.sleep(1) print(i) i+=1 return layout = [ [sg.Text('current state:'), sg.Text(key='-STATE_OUT-')], [sg.Text('limit'), sg.Input(key='-LIMIT-', s=5)], [sg.Button('start counting')] ] window = sg.Window('thread and GUI testing',layout) while True: event, values = window.read() if event == sg.WIN_CLOSED: break if event == 'start counting': timelimit = float(values['-LIMIT-']) window['-STATE_OUT-'].update('count starting') c_thread = threading.Thread(target=side_thread, kwargs={'limit': timelimit}) c_thread.start() # if side thread has returned then continue c_thread.join() window['-STATE_OUT-'].update('count finished')
期望流程
- 点击“start counting”按钮;
- 显示文本“current state: count starting”;
- 程序开始计数至设定上限,且GUI不冻结;
- 显示文本“current state: count finished”。
但实际情况是点击按钮后GUI立即冻结(“count starting”不显示),直到循环结束才显示“count finished”。
之后尝试使用window.TKroot.after():
window = sg.Window('thread and GUI testing',layout) while True: event, values = window.read() if event == sg.WIN_CLOSED: break if event == 'start counting': timelimit = float(values['-LIMIT-']) window['-STATE_OUT-'].update('count starting') i=0 while i<timelimit: window.TKroot.after(1000) print(i) i+=1 window['-STATE_OUT-'].update('count finished')
但问题依旧。
后续疑问:能否在for循环中实现write_event_value?
示例代码如下:
import threading import time import PySimpleGUI as sg layout = [ [sg.Text('Counting Sequence')], [sg.Text('current progress'), sg.Text(key='-PR_OUT-')], [sg.Text('repeat count'), sg.Text(key='-RC_OUT-')], [sg.Text('set repeat count'), sg.Input(key='-Set_RC-', s=10)], [sg.Button('start sequence')] ] def sequence_thread(limit): i=0 while i<=limit: time.sleep(1) print(i) i+=1 return window = sg.Window('thread and GUI testing',layout) while True: event, values = window.read() if event == sg.WIN_CLOSED: break if event == 'start sequence': endpoint = int(values['-Set_RC-']) window['-PR_OUT-'].update('sequence starting') for i in range(endpoint): c_thread = threading.Thread(target=sequence_thread, args=(3,)) c_thread.start() c_thread.join() rep_count = i+1 window['-RC_OUT-'].update(str(rep_count)) window['-PR_OUT-'].update('sequence finished') window.close()
内容的提问来源于stack exchange,提问作者user1121
相关产品推荐
相关产品推荐

