简体   繁体   English

Winsound 导致我的 tkinter GUI 打开缓慢

[英]Winsound causing my tkinter GUI to open slowly

I'm working on a tkinter GUI in Python to produce error messages in a new window.我正在使用 Python 开发 tkinter GUI,以在新窗口中生成错误消息。 When running the code as shown below, the error noise plays, then it pauses for several seconds before opening the window.运行如下所示的代码时,会播放错误噪音,然后在打开窗口之前暂停几秒钟。 If I comment out the line with winsound, it opens it just fine.如果我用 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()

I suspect that it may be due to the error noise playing in full before reaching the mainloop command.我怀疑这可能是由于在到达 mainloop 命令之前完全播放了错误噪声。 One solution to this could be running the sound in a separate thread, but I've heard multithreading with tkinter should be avoided.对此的一种解决方案可能是在单独的线程中运行声音,但我听说应该避免使用 tkinter 进行多线程处理。 Any tips on getting it to open smoothly at the same time as the noise is played?在播放噪音的同时让它顺利打开有什么技巧吗?

Try this, the reason why it does that is the whole program is should we say in ONE THREAD/ MAIN THREAD so it would do first or execute first the sound then pop up the window.试试这个,它这样做的原因是整个程序是我们应该在一个线程/主线程中说这样它会先做还是先执行声音然后弹出窗口。 I think there's no problem with working with threads in tkinter just like what @jasonharper said我认为在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM