我使用PySimpleGui制作一个简单的文件格式转换程序,但是我的程序的小窗口一直告诉我(没有响应),就像它在实际工作和编写新文件时被压碎了一样。
问题是循环,如果我删除它,一切正常,但用户对转换的进展没有任何反应。我编写了一些关于python线程的文档,我认为一切都应该正常工作,有什么建议吗?这是代码:‘
def main():
sg.theme('DarkGrey3')
layout1 = [[sg.Text('File converter (.csv to sdf)')],
[sg.Frame('Input Filename',
[[sg.Input(key='-IN-'), sg.FileBrowse(), ],])],
[sg.Frame('Output Path',
[[sg.Input(key='-OUT-'), sg.FolderBrowse(), ],])],
[sg.Button('Convert'), sg.Button('Exit')], [sg.Text('', key='-c-')]]
window=sg.Window(title='.csv to .sdf file converter', layout=layout1, margins=(50, 25))
window.read()
while True:
event, values = window.read()
if event=='Exit' or event==None:
break
if event=='Convert':
csvfilepath=values['-IN-']
outpath=values['-OUT-']
x=threading.Thread(target=Converter, args=[csvfilepath, outpath])
x.start()
time.sleep(1)
while x.is_alive():
window['-c-'].Update('Conversion')
time.sleep(1)
window['-c-'].Update('Conversion.')
time.sleep(1)
window['-c-'].Update('Conversion..')
time.sleep(1)
window['-c-'].Update('Conversion...')
time.sleep(1)`
发布于 2022-11-14 00:24:16
您的代码正在按预期工作。窗口没有响应,因为您有一个阻塞主线程的while循环。主线程负责处理事件和更新窗口。
有几种方法可以解决这个问题。一个是将while循环移动到一个单独的线程中。另一种方法是使用PySimpleGUI的内置进度条特性。
下面是如何使用进度条的示例:
import PySimpleGUI as sg
layout = [[sg.Text('Progress Bar')],
[sg.ProgressBar(1000, orientation='h', size=(20, 20), key='progress')],
[sg.Cancel()]]
window = sg.Window('Window Title', layout)
progress_bar = window['progress']
for i in range(1000):
# update progress bar with loop value +1 so that bar reaches the end
event, values = window.read(timeout=0)
if event == 'Cancel' or event == sg.WIN_CLOSED:
break
progress_bar.UpdateBar(i + 1)
window.close()发布于 2022-11-14 05:09:09
下面的代码演示如何通过超时事件和线程更新GUI。
import time
import threading
import PySimpleGUI as sg
def convert_func(window):
for i in range(10): # Simuate the conversion
window.write_event_value('Conversion Step', i)
time.sleep(1)
window.write_event_value('Conversion Done', None)
layout = [
[sg.Button('Convert'), sg.Text('', expand_x=True, key='Step')],
[sg.StatusBar('', size=20, key='Status')],
]
window = sg.Window('Title', layout, finalize=True)
status, step = window['Status'], window['Step']
running, index, m = False, 0, 10
msg = ['Conversion'+'.'*i for i in range(m)]
while True:
event, values = window.read(timeout=200)
if event == sg.WIN_CLOSED:
break
elif event == 'Convert':
threading.Thread(target=convert_func, args=(window,), daemon=True).start()
running = True
elif event == sg.TIMEOUT_EVENT and running:
status.update(msg[index])
index = (index + 1) % m
elif event == 'Conversion Step':
print(event)
i = values[event]
step.update(f'Step {values[event]}')
elif event == 'Conversion Done':
running = False
step.update('')
status.update(event)
window.close()

https://stackoverflow.com/questions/74425822
复制相似问题