因此,我進行了廣泛的嘗試來找出運行代碼的最佳方法。最好的建議是遞歸運行 root.after 直到滿足條件。這有效,但它會凍結(jié)窗口,直到滿足條件。我不知道出了什么問題或如何解決這個問題。我想顯示 tkinter 對話框窗口,每 1000 毫秒檢查一次是否滿足條件,一旦滿足就允許“下一步”按鈕變得可單擊。這一切都有效,除非條件從未滿足,否則無法退出程序,因為導航欄卡在“無響應”狀態(tài)。我真的需要這個導航欄不被搞亂。與關閉按鈕相比,我更喜歡它。這是代碼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()
1 回答

慕神8447489
TA貢獻1780條經(jīng)驗 獲得超1個贊
root.after(1000)實際上與time.sleep(1)- 它凍結(jié) UI 直到時間到期相同。它不允許事件循環(huán)處理事件。
如果您想checkForPortConnection每秒調(diào)用一次,這是正確的方法:
def checkForPortConnection(root, initial_ports):
new_ports = listSerialPorts()
if initial_ports == new_ports:
root.after(1000, checkForPortConnection, root, initial_ports)
checkForPortConnection這將在未來(或多或少)調(diào)用一秒鐘,傳遞root和initial_ports作為參數(shù)。每次運行時,它都會安排自己在將來再次運行,直到不再滿足條件為止。
在該時間段到期之前,mainloop能夠繼續(xù)正常處理事件。
添加回答
舉報
0/150
提交
取消