简体   繁体   中英

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. 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.

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. One solution to this could be running the sound in a separate thread, but I've heard multithreading with tkinter should be avoided. 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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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