首页 > 解决方案 > 如何停止或结束一个线程然后重新启动它?

问题描述

这是我尝试过的蛇游戏,但出现错误。

我确实想出了另一种方法,

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

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

import playsound
import threading
import time

def coin():
    playsound.playsound('coin.mp3')

ding = threading.Tread(target=coin)

ding.start()

time.sleep(5)

ding.start()

RuntimeError:线程只能启动一次

标签: pythonmultithreadingpython-multithreadingpython-playsound

解决方案


试试这个,它对我有用。来源: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)

推荐阅读