Search code examples
pythonturtle-graphics

I'm having this error bad event type or key in making snake game, by using turtle graphic in PyCharm


from turtle import Turtle

STARTING_POSITION = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20


class Snake:

    def __init__(self):


        self.adding_dots = []
        self.create_snake()
        self.head = self.adding_dots[0]


    def create_snake(self):
        for position in STARTING_POSITION:
            segment = Turtle("square")
            segment.color("white")
            segment.penup()
            segment.goto(position)
            self.adding_dots.append(segment)

    def move(self):
        for moving in range(len(self.adding_dots) - 1, 0, - 1):
            new_x = self.adding_dots[moving - 1].xcor()
            new_y = self.adding_dots[moving - 1].ycor()
            self.adding_dots[moving].goto(new_x, new_y)
        self.head[0].forward(MOVE_DISTANCE)

    def up(self):
        self.head.setheading(90)

    def down(self):
        self.head.setheading(270)

    def left(self):
        self.head.setheading(180)

    def right(self):
        self.head.setheading(0)

Traceback (most recent call last):
  File "C:\Users\Kiran\PycharmProjects\Day_20\main.py", line 14, in <module>
    screen.onkey(game.up, "up")
  File "C:\Users\Kiran\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 1395, in onkey
    self._onkeyrelease(fun, key)
  File "C:\Users\Kiran\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 686, in _onkeyrelease
    self.cv.bind("<KeyRelease-%s>" % key, eventfun)
  File "C:\Users\Kiran\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 417, in bind
    self._canvas.bind(*args, **kwargs)
  File "C:\Users\Kiran\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1421, in bind
    return self._bind(('bind', self._w), sequence, func, add)
  File "C:\Users\Kiran\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1375, in _bind
    self.tk.call(what + (sequence, cmd))
_tkinter.TclError: bad event type or keysym "up"

Solution

  • The issue is in the direction control part, you should use uppercase for the first letter. on your main.py, line 14 It should be

    screen.onkey(game.up, "Up")
    

    The same for the other directions ->Up, Down, Left, Right