Reputation: 55
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?
Upvotes: 3
Views: 1282
Reputation: 11
This will help you:
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)
def printtext():
threadsound = threading.Thread(target=playsound)
threadsound.start()
print("Hi")
button = Button(root, text=("button"), command=printtext)
button.pack()
root.mainloop()
I have did a little bit changes in your program to make it run in the way you specified.
If you got any error while in the execution of this code then share it also.
Upvotes: 1
Reputation: 55
So, I ended up scrapping that bit of code and replacing it with the pygame module because I find it more flexible, but yeah, moving threadsound = ... into printtext() as acw1668 pointed out solves the issue I was having with the thread
thank you so much acw1668
Upvotes: 1