I want to call a function (trigger) that will hide one image, show another image and play a sound. The sound has to play last as it lasts for several seconds locking everything up. When I call the function my alarm sound plays for several seconds then an image is shown showing which sensor has triggered (the original image does not hide not sure what I’m doing wrong there yet so commented out only dealing with one issue at a time).
First I searched my code for other uses of the word “trigger” to see if I was calling another function.
I put the image display line in brackets.
Added a 1 sec delay in between the image displaying and the sound playing.
Tried having my alarm sound in another function that is called by the image display function, so press button calls image display function, image display function calls play sound function.
Every time the sound plays and then when it finished the image shows. Whilst the sound is playing the program is locked up.
Button(root, text='Trigger Security', bg='#F0F8FF', font=('arial', 12, 'normal'), command=trigger).place(x=10, y=95) def trigger(): #canvas.create_image(260,-70, anchor=NW, image=bowstbradarm, state='hidden') canvas.create_image(260,-70, anchor=NW, image=bowstbradar, state='normal') playsound("tng_red_alert1.mp3")
Is it possible to run 2 functions at the same time so my program doesn’t lock up?
I’m on ubuntu using IDLE if that helps at all.
Advertisement
Answer
It is because playsound()
is a blocking function by default, so it blocks the tkinter mainloop from updating until the sound file is played completely.
You can execute playsound()
in non-blocking mode by passing False
as the second argument:
playsound("tng_red_alert1.mp3", False)
Update: As block=False
is not supported in Linux, you need to use thread to execute playsound()
:
import threading ... threading.Thread(target=playsound, args=("tng_red_alert1.mp3",)).start()