【发布时间】:2021-12-27 14:58:58
【问题描述】:
我正在尝试在 python 中使用 pysimplegui 实现 asyncio。 在这个 GUI 示例中,两个按钮(按钮 2 和按钮 3)模拟了一个很长的任务来完成。
目标:
- 即使调用的函数(通过按钮)需要时间来返回结果,也能够返回 GUI 界面。
预期结果:
- 如果按钮 2 或按钮 3 或两者都被按下,它们都会继续执行其任务,用户可以返回 GUI 继续执行其他任务。
当前结果:
- 只要按下按钮 2 或按钮 3,任务就会被阻止并持续到结束,而 GUI 会挂起直到结束。
import PySimpleGUI as sg
import asyncio
import time
sg.theme('Light Blue 3')
# This design pattern simulates button callbacks
# This implementation uses a simple "Dispatch Dictionary" to store events and functions
# The callback functions
async def button1():
print('Button 1 callback')
return 'nothing'
async def button2():
print('Button 2 callback')
for i in range(1,20):
await asyncio.sleep(3)
print(f"Button 2: {i}")
return f"button2 end"
async def button3():
print('Button 3 callback')
for i in range(1,10):
await asyncio.sleep(3)
print(f"Button 3: {i}")
return f"button3: end"
# Lookup dictionary that maps button to function to call
dispatch_dictionary = {'1':button1, '2':button2, '3':button3}
# Layout the design of the GUI
layout = [[sg.Text('Please click a button', auto_size_text=True)],
[sg.Button('1'), sg.Button('2'), sg.Button('3'), sg.Quit()]]
# Show the Window to the user__TIMEOUT__
window = sg.Window('Button callback example', layout)
# Event loop. Read buttons, make callbacks
while True:
# Read the Window
event, values = window.read()
if event in ('Quit', sg.WIN_CLOSED):
break
if event == '__TIMEOUT__':
continue
# Lookup event in function dictionary
if event in dispatch_dictionary:
func_to_call = dispatch_dictionary[event] # get function from dispatch dictionary
print(asyncio.run(func_to_call()))
else:
print('Event {} not in dispatch dictionary'.format(event))
window.close()
# All done!
sg.popup_ok('Done')
我以为我按照规则应用了异步/等待。我错过了什么吗?
【问题讨论】:
标签: python python-asyncio pysimplegui