简体   繁体   中英

I'm getting an error message: _tkinter.TclError: bad event type or keysym "ButtonLeft"

My code:

def left():
    a.bk(25)
def right():
    a.fd(25)
def up():
    a.lt(90)
    a.fd(25)
    a.rt(90)
def down():
    a.rt(90)
    a.fd(25)
    a.lt(90)
while True:
    a.onrelease(left,"Left")
    a.onrelease(right,"Right")
    a.onrelease(up,"Up")
    a.onrelease(down,"Down")
    a.listen()

How do I fix this? I'd also prefer to use onkey instead of onrelease but it gives me an error message: 'Turtle' object has no attribute 'onkey'

onrelease() , onclick() , ondrag() are for mouse's buttons - and it needs numbers 1 (left button), 2 (middle button), 3 (right button). Probably it may also use 4 and 5 if mouse has more buttons. They are assigned to turtles and they need a.onrelease()

onkey() , onkeyrelease() , onkeypress() are for keyboard's keys - but keys are not assigned to turtles and you should use directly turtle.onkey() or you should create screen = turtle.Screen() and use screen.onkey()

And you don't have to run code in while -loop but use turtle.mainloop() or turtle.done() .

import turtle

# --- functions ---  # PEP8: all functions before main code

def left():
    a.bk(25)
    
def right():
    a.fd(25)
    
def up():
    a.lt(90)
    a.fd(25)
    a.rt(90)
    
def down():
    a.rt(90)
    a.fd(25)
    a.lt(90)

def turle_clicked(x, y):
    print('turtle:', x, y)

def screen_clicked(x, y):
    print('screen:', x, y)

# --- main ---

a = turtle.Turtle()

a.onrelease(turle_clicked, 1)  # left button (clicked on turtle)
a.onrelease(turle_clicked, 2)  # middle button (clicked on turtle)
a.onrelease(turle_clicked, 3)  # right button (clicked on turtle)

turtle.onscreenclick(screen_clicked, 1)  # left button  (clicked in any place in window)

turtle.onkey(left,"Left")
turtle.onkey(right,"Right")
turtle.onkey(up,"Up")
turtle.onkey(down,"Down")
        
turtle.listen()

turtle.mainloop()

PEP 8 -- Style Guide for Python Code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM