我正在使用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多线程。有什么技巧可以让它在播放噪音的同时顺利打开?
答案 0 :(得分:0)
尝试一下,之所以要这样做是整个程序,是因为我们应该在一键/主键中说一遍,以便它先执行还是先执行声音,然后弹出窗口。我认为使用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")