[英]Winsound causing my tkinter GUI to open slowly
我正在使用 Python 開發 tkinter GUI,以在新窗口中生成錯誤消息。 運行如下所示的代碼時,會播放錯誤噪音,然后在打開窗口之前暫停幾秒鍾。 如果我用 winsound 注釋掉該行,它會打開它就好了。
import tkinter as tk
import winsound
class 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()
我懷疑這可能是由於在到達 mainloop 命令之前完全播放了錯誤噪聲。 對此的一種解決方案可能是在單獨的線程中運行聲音,但我聽說應該避免使用 tkinter 進行多線程處理。 在播放噪音的同時讓它順利打開有什么技巧嗎?
試試這個,它這樣做的原因是整個程序是我們應該在一個線程/主線程中說這樣它會先做還是先執行聲音然后彈出窗口。 我認為在 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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.