I'm trying to code a program in Python 3 running Windows 7. I want the program to be able to display text in a window and play an audio file at the same time. I can successfully complete both processes at different times. How do I complete these processes at the same time? Here is a code block taken from the program:
import lipgui, winsound, threading
menu = lipgui.enterbox("Enter a string:")
if menu == "what's up, lip?":
t1 = threading.Thread(target=winsound.PlaySound("C:/Interactive Program/LIP Source Files/skyisup.wav", 2), args=(None))
t2 = threading.Thread(target=lipgui.msgbox("The sky is up"), args = (None))
-
Can you please show more code ahead from where you have given. What happens in your current code? It should work and make both run at the same time.Ramchandra Apte– Ramchandra Apte2013年10月20日 15:45:33 +00:00Commented Oct 20, 2013 at 15:45
-
Edited it. This is the full script. It still does them at separate times!Luke Dinkler– Luke Dinkler2014年03月04日 20:33:37 +00:00Commented Mar 4, 2014 at 20:33
1 Answer 1
The target argument of Thread must point to a function to execute. Your code evaluates the function before passing it to target.
t1 = threading.Thread(target=winsound.PlaySound("C:/Interactive Program/LIP Source Files/skyisup.wav", 2), args=(None))
t2 = threading.Thread(target=lipgui.msgbox("The sky is up."), args = (None))
is functionally the same as:
val1 = winsound.PlaySound("C:/Interactive Program/LIP Source Files/skyisup.wav", 2)
t1 = threading.Thread(target=val1, args=(None))
val2 = lipgui.msgbox("The sky is up.")
t2 = threading.Thread(target=val2, args=(None))
What you actually want to do is pass only the function to target before it's evaluated and pass the arguments you want to pass to the desired function in the args parameter when instantiating Thread.
t1 = threading.Thread(target=winsound.PlaySound, args=("C:/Interactive Program/LIP Source Files/skyisup.wav", 2))
t2 = threading.Thread(target=lipgui.msgbox, args=("The sky is up.",))
Now t1 and t2 contain Thread instances with references to the functions you want to run in parallel along with the arguments. They still aren't running the code yet. To do that you need to run:
t1.start()
t2.start()
Make sure you don't call t1.run() or t2.run(). run() is a method of Thread that start() normally runs in a new thread.
The final code should be:
import lipgui
import winsound
import threading
menu = lipgui.enterbox("Enter a string:")
if menu == "what's up, lip?":
t1 = threading.Thread(target=winsound.PlaySound, args=("C:/Interactive Program/LIP Source Files/skyisup.wav", 2))
t2 = threading.Thread(target=lipgui.msgbox, args=("The sky is up",))
t1.start()
t2.start()