0

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*

SuperByte
  • 7
  • 5
  • Forward/backward is not the same as left/right/up/down. One is relative to the turtle, the others are relative to the screen. – mozway Dec 21 '21 at 00:31

1 Answers1

0

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? (E.g. 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()
cdlane
  • 40,441
  • 5
  • 32
  • 81
  • I am on the one on replit, and sorry for the function error, it wasn't the original code – SuperByte Dec 21 '21 at 23:24
  • I have a question, the thing was I was coding with the `from turtle import *` edition, so is there any difference? – SuperByte Dec 21 '21 at 23:28
  • @SuperByte, you can rework my example to use `from turtle import *`. But I don't recommend it. Standard Python turtle exposes two APIs, a *functional* one and and an *object oriented one*. Using the `import` I specified, only brings in the object API and block the functional one. Other `import` methods can bring in both, allowing mixing, which can cause misunderstandings and problems. – cdlane Dec 22 '21 at 02:08