Search code examples
pythonpython-turtlepython-playsound

Turtle crashes while playing music with playsound2


I have simple python turtle code which works fine, but when I add music, music plays, but turtle program crashes. What are the fixes for that? Here is my code:

import turtle
import playsound2

t = turtle.Turtle()

playsound2.playsound("song.mp3")

t.forward(50)

turtle.mainloop()

Solution

  • All python code below line 6 will not execute until music stops playing. You need two create two separate threads: one for your turtle code and one for music. You can do that this way:

    import turtle
    import playsound2
    from threading import Thread
    
    def play_music():
        playsound2.playsound("song.mp3")
    
    def turtle_code():
        t = turtle.Turtle()
        t.forward(50)
    
        turtle.mainloop()
    
    thread1 = Thread(target=play_music)
    thread2 = Thread(target=turtle_code)
    thread1.start()
    thread2.start()