我正在使用 Python 開發 tkinter GUI,以在新窗口中生成錯誤消息。運行如下所示的代碼時,會播放錯誤噪音,然后暫停幾秒鐘,然后打開窗口。如果我用winsound注釋掉該行,它就可以很好地打開它。import tkinter as tkimport winsoundclass Error_Window: def __init__(self, txt): self.root = tk.Tk() self.root.title("Error") self.lbl = tk.Label(self.root, text=txt) self.lbl.pack() winsound.PlaySound("SystemExit", winsound.SND_ALIAS) self.root.mainloop()我懷疑這可能是由于在到達主循環命令之前完全播放錯誤噪音所致。解決此問題的一種方法是在單獨的線程中運行聲音,但我聽說應該避免使用 tkinter 進行多線程處理。有什么技巧可以讓它在播放噪音的同時順利打開嗎?
1 回答

弒天下
TA貢獻1818條經驗 獲得超8個贊
試試這個,它這樣做的原因是整個程序是我們應該說在一個線程/主線程中,這樣它會首先執行或先執行聲音,然后彈出窗口。我認為在 tkinter 中使用線程沒有問題,就像 @jasonharper 所說的那樣
import tkinter as tk
import winsound
import threading
class Error_Window:
def __init__(self, txt):
self.root = tk.Tk()
self.root.title("Error")
self.lbl = tk.Label(self.root, text=txt)
th = threading.Thread(target=self.__play_sound,args=[])
th.start()
self.lbl.pack()
self.root.mainloop()
def __play_sound(self):
winsound.PlaySound("SystemExit", winsound.SND_ALIAS)
Error_Window("Hi")
添加回答
舉報
0/150
提交
取消