Turtle graphics crashing

144 views Asked by At

Help, i'm trying to make a turtle graphics program that uses keyboard to control the direction of the turtle but every time i open it, it keeps crashing!!

import keyboard
from turtle import *
keyboard.add_hotkey('Up arrow', lambda:
                    forward(2))
keyboard.add_hotkey('Left arrow', lambda:
                    left(2))
keyboard.add_hotkey('right arrow', lambda:
                    right(2))
1

There are 1 answers

0
cdlane On

First, we don't need the keboard module to move the turtle around the screen with the keyboard, we can use turtle's own keyboard events:

import turtle

turtle.shape("turtle")

turtle.onkey(lambda: turtle.forward(20), "Up")
turtle.onkey(lambda: turtle.left(45), "Left")
turtle.onkey(lambda: turtle.right(45), "Right")

turtle.listen()
turtle.mainloop()

Make sure to click on the window to activate it before typing. If you really want to use the keybard module, this seems to have worked for me:

import turtle
import keyboard

turtle.shape("turtle")

keyboard.add_hotkey('up arrow', turtle.forward, args=[20])
keyboard.add_hotkey('left arrow', turtle.left, args=[45])
keyboard.add_hotkey('right arrow', turtle.right, args=[45])

turtle.mainloop()

You can also use a lambda variant:

keyboard.add_hotkey('right arrow', lambda: turtle.right(45))

Though on my system (OSX) it was difficult to work with (single key press generated multiple events that didn't fire until later key presses, wanted to run as admin, etc.)