I've been tinkering with a Tkinter project that I finished a couple of days ago and I wanted to add some sounds to make it a bit more interesting.
I added button sounds with winsound like this:
(simplified code)
import winsound
from Tkinter import *
root = Tk()
canvas = Canvas(root, height=500, width=500)
canvas.pack()
def printtext():
winsound.PlaySound("button.wav", winsound.SND_ALIAS)
print("Hi")
button = Button(root, text=("button"), command=printtext)
button.pack()
root.mainloop()
This technically works but, since the code runs synchronously the GUI freezes until the sound plays in its entirety.
To solve this problem, I used threads to play the sound in the background while the rest of the function runs.
like this:
(simplified code)
import winsound
import threading
from tkinter import *
root = Tk()
canvas = Canvas(root, height=500, width=500)
canvas.pack()
def playsound():
winsound.PlaySound("button.wav", winsound.SND_ALIAS)
threadsound = threading.Thread(target=playsound)
def printtext():
threadsound.start()
print("Hi")
button = Button(root, text=("button"), command=printtext)
button.pack()
root.mainloop()
Again, it technically works, but threads can only be started once, so I'm stuck here.
Is there another way to achieve this?