简体   繁体   中英

Up arrow key not working for python turtle

I have used the onkey function for the right and left:

sc.onkey(user_left,"left")
sc.onkey(user_right,"right")

I have also set the screen after setting the turtle and importing turtle:

sc=Screen()

But when I use the same format for up and down:

sc.onkey(user_up,"up")
sc.onkey(user_down,"down")

It does nothing. I also have my functions:

def user_right:
   t3.forward(5)
def user_left:
   t3.backward(5)

t3 is my user turtle, and it is sideways, the shape is turtle, and its head is facing right. t3 is automatically set to make its head facing the right side when the code runs. By the way, I import from turtle import*

I see several issues here. First, this can't work as you claim:

def user_right:
    t3.forward(5)
def user_left:
    t3.backward(5)

It would need to be:

def user_right():
    t3.forward(5)
def user_left():
    t3.backward(5)

Next, this won't work in turtle in standard Python:

sc.onkey(user_left,"left")
sc.onkey(user_right,"right")

These keys would have to be "Left" and "Right" . Are you using a non-standard turtle implementation? (Eg the one on repl.it) You show your two event handlers that work, but fail to show the two that don't which would be of more interest when trying to debug your code.

Finally, your missing a call to the screen's listen() method, so your keystrokes are ignored. Here's how I might implement the functionality your code is hinting at:

from turtle import Screen, Turtle

def user_right():
    turtle.forward(5)

def user_left():
    turtle.backward(5)

def user_up():
    turtle.sety(turtle.ycor() + 5)

def user_down():
    turtle.sety(turtle.ycor() - 5)

turtle = Turtle()
turtle.shape('turtle')

screen = Screen()

screen.onkey(user_left, 'Left')
screen.onkey(user_right, 'Right')
screen.onkey(user_up, 'Up')
screen.onkey(user_down, 'Down')

screen.listen()
screen.mainloop()

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