2

我正在尝试在运行 Windows 7 的 Python 3 中编写程序。我希望程序能够在窗口中显示文本并同时播放音频文件。我可以在不同的时间成功完成这两个过程。如何同时完成这些过程?这是从程序中提取的代码块:

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

1 回答 1

2

target参数Thread必须指向要执行的函数。您的代码在将函数传递给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 之前args只将函数传递给它,并在实例化时将要传递的参数传递给参数中的所需函数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.",))

现在 t1 和 t2 包含 Thread 实例,其中引用了要与参数一起并行运行的函数。他们还没有运行代码。为此,您需要运行:

t1.start()
t2.start()

确保你不打电话t1.run()t2.run()run()是 Thread 的一种方法,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()
于 2013-11-07T17:12:07.290 回答