2013-10-13 47 views
2

我想在运行Windows 7的Python 3中编写程序。我希望程序能够在窗口中显示文本并同时播放音频文件。我可以在不同的时间顺利完成这两个流程。我如何在同一时间完成这些流程?下面是从程序取的代码块:如何在Python中一次运行2个不同的进程

 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)) 
+0

能否请您提前从已给出,其中表现出更多的代码。你现在的代码发生了什么?它应该工作,并使两者同时运行。 –

+0

编辑它。这是完整的脚本。它仍然在不同的时间做它们! –

回答

2

Threadtarget参数必须指向以执行功能。您的代码在将其传递给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)) 

在功能上等同于:

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)) 

你真正想要做的是只传递它是评估前的功能target并传递要传递给参数在实例化Thread时参数args中的所需功能。

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和t2包含线程实例,其中引用了您想要与参数并行运行的函数。他们仍然没有运行代码。要做到这一点,你需要运行:

t1.start() 
t2.start() 

确保你不叫t1.run()t2.run()run()是线程的一种方法,start()通常在新线程中运行。

最后的代码应该是:

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() 
+0

对不起,回复迟!现在,当我运行它时,它播放音频,程序继续运行,但它不显示GUI! –

+0

你好?我仍然无法弄清楚这一点! –

+0

你能发布一些更新的代码吗? –

相关问题