0

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?

csulli245
  • 140
  • 7
  • `winsound` has a `SND_ASYNC` or similar flag to play the sound in the background. And a separate thread would also be a workable solution - Tkinter has no problem with that, as long as you're not making any Tkinter calls from anything other than the main thread. – jasonharper Oct 07 '20 at 13:05
  • multithreading should work fine as long as you don't call tkinter objects from more than one thread. Calling winsound in a separate thread should work fine. – Bryan Oakley Oct 07 '20 at 13:37
  • @BryanOakley Oh so if i have two function in a tkinter window in two different threads and tkinter is in another thread, it would make some problems? – Delrius Euphoria Oct 07 '20 at 14:44
  • 1
    @CoolCloud: you should only access tkinter objects from a single thread. This is from someone who actually wrote some of the tk code: http://stackoverflow.com/a/38767665/7432 – Bryan Oakley Oct 07 '20 at 14:47

1 Answers1

1

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")
Ice Bear
  • 2,676
  • 1
  • 8
  • 24