因此,我進(jìn)行了廣泛的嘗試來(lái)找出運(yùn)行代碼的最佳方法。最好的建議是遞歸運(yùn)行 root.after 直到滿足條件。這有效,但它會(huì)凍結(jié)窗口,直到滿足條件。我不知道出了什么問(wèn)題或如何解決這個(gè)問(wèn)題。我想顯示 tkinter 對(duì)話框窗口,每 1000 毫秒檢查一次是否滿足條件,一旦滿足就允許“下一步”按鈕變得可單擊。這一切都有效,除非條件從未滿足,否則無(wú)法退出程序,因?yàn)閷?dǎo)航欄卡在“無(wú)響應(yīng)”狀態(tài)。我真的需要這個(gè)導(dǎo)航欄不被搞亂。與關(guān)閉按鈕相比,我更喜歡它。這是代碼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貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
root.after(1000)實(shí)際上與time.sleep(1)- 它凍結(jié) UI 直到時(shí)間到期相同。它不允許事件循環(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這將在未來(lái)(或多或少)調(diào)用一秒鐘,傳遞root和initial_ports作為參數(shù)。每次運(yùn)行時(shí),它都會(huì)安排自己在將來(lái)再次運(yùn)行,直到不再滿足條件為止。
在該時(shí)間段到期之前,mainloop能夠繼續(xù)正常處理事件。
添加回答
舉報(bào)
0/150
提交
取消