如何停止或结束线程,然后重新启动它?



这是我尝试过贪吃蛇游戏的东西,但我得到了一个错误。

我确实想出了另一种方法

,(即每次蛇碰到硬币时重新定义线程(

但我仍然对问题是什么以及如何解决它感到困惑。

import playsound
import threading
import time
def coin():
playsound.playsound('coin.mp3')
ding = threading.Tread(target=coin)
ding.start()
time.sleep(5)
ding.start()

运行时错误:线程只能启动一次

试试这个,它对我有用。来源: https://stackoverflow.com/a/20021547/13300960

from pygame import mixer  # pip install pygame
import threading
import time

def coin():
mixer.init()
mixer.music.load(r"coin.mp3")
mixer.music.play()

threading.Thread(target=coin).start()
time.sleep(5)
threading.Thread(target=coin).start()
time.sleep(5)

最新更新