python - tkinter root.after 运行直到满足条件,冻结窗口导航栏直到满足条件。为什么?
问题描述
所以我已经广泛尝试找出运行我的代码的最佳方式。最好的建议是递归运行 root.after 直到满足条件。这可行,但它会冻结窗口,直到满足条件。我无法弄清楚出了什么问题或如何解决这个问题。我想显示 tkinter 对话窗口,每 1000 毫秒检查一次是否满足条件,一旦满足允许“NEXT”按钮变为可点击。这一切都有效,除非条件从未满足,没有办法退出程序,因为导航栏卡在“无响应”中。我真的需要这个导航栏不要搞砸。我更喜欢它而不是关闭按钮。这是代码
def checkForPortConnection(root, initial_ports):
new_ports = listSerialPorts()
root.after(1000)
if initial_ports == new_ports:
checkForPortConnection(root, initial_ports)
else:
return
def welcomeGui():
root = tk.Tk()
root.title('Setup Wizard')
canvas1 = tk.Canvas(root, relief = 'flat')
welcome_text='Welcome to the setup wizard for your device'
text2 = 'Please plug your device into a working USB port'
text3 = 'If you have already plugged it in, please unplug it and restart the wizard. \n Do not plug it in until the wizard starts. \n The "NEXT" button will be clickable once the port is detected'
label1 = tk.Label(root, text=welcome_text, font=('helvetica', 18), bg='dark green', fg='light green').pack()
label2 = tk.Label(root, text=text2, font=('times', 14), fg='red').pack()
label3 = tk.Label(root, text=text3, font=('times', 12)).pack()
nextButton = ttk.Button(root, text="NEXT", state='disabled')
nextButton.pack()
initial_ports = listSerialPorts()
root.update()
checkForPortConnection(root, initial_ports)
new_ports = listSerialPorts()
correct_port = [x for x in initial_ports + new_ports if x not in initial_ports or x not in new_ports]
print(correct_port)
nextButton.state(["!disabled"])
root.mainloop()
解决方案
root.after(1000)
实际上与time.sleep(1)
- 它冻结 UI 直到时间到期。它不允许事件循环处理事件。
如果您想每秒调用checkForPortConnection
一次,这是正确的方法:
def checkForPortConnection(root, initial_ports):
new_ports = listSerialPorts()
if initial_ports == new_ports:
root.after(1000, checkForPortConnection, root, initial_ports)
checkForPortConnection
这将在未来(或多或少)调用一秒钟,传递root
和initial_ports
作为参数。每次运行时,它都会安排自己在未来再次运行,直到不再满足条件。
直到时间段到期,mainloop
才能继续正常处理事件。
推荐阅读
- c# - dotnet WebApi 如何获取用户附近的位置
- javascript - 如何使搜索列表更短?
- spring - 如何在 JPA 存储库的自定义方法中使用规范
- javascript - 我想将此 Flatlist 反应本机代码转换为类文件
- java - 使用 AsyncTask 读取 Firestore 文档
- postgresql-9.6 - 一个父表可以参与多少个子表?
- swift - FileManager.replaceItem 删除原始项目
- javascript - columDefs 和 columns 是互斥的吗?
- google-cloud-platform - 在bigquery中将多列变成一行
- cplex - 基准测试中不同答案的原因