Reputation: 1
I have made a program in which I want to use the onkey()
function, but it is not working, it is like none of the keys of my keyboard work:
from turtle import*
import sys
s=Screen()
s.setup(500,500)
s.title("title")
x=Turtle(shape=image)
def e1():
print("hello")
s.bye()
def k1():
x.fd(40)
def k2():
x.lt(90)
def k3():
x.rt(90)
def k4():
x.bk(20)
s.onkey(e1,"Escape")
s.onkey(k1,"w")
s.onkey(k2,"a")
s.onkey(k3,"s")
s.onkey(k4,"z")
s.listen()
Upvotes: 0
Views: 1097
Reputation: 67
This happened to me as well. I figured out that in Spyder IDE, you need to first import 'mainloop' and at the end, call it, as cdlane has stated above; now the code works!
from turtle import Turtle, Screen, mainloop
tim = Turtle()
screen = Screen()
def move_forwards():
tim.forward(10)
screen.listen()
screen.onkeypress(fun = move_forwards, key = "space")
mainloop()
Upvotes: 1
Reputation: 41872
Except for a missing image
variable, your code works for me under Python 2.7.10 -- my rework of your code:
from turtle import Turtle, Screen, mainloop
def e1():
print("goodbye")
screen.bye()
def k1():
turtle.forward(40)
def k2():
turtle.left(90)
def k3():
turtle.right(90)
def k4():
turtle.backward(20)
screen = Screen()
screen.setup(500, 500)
screen.title("title")
turtle = Turtle(shape="turtle")
screen.onkey(e1, "Escape")
screen.onkey(k1, "w")
screen.onkey(k2, "a")
screen.onkey(k3, "s")
screen.onkey(k4, "z")
screen.listen()
mainloop()
One possibility is you're not clicking on the turtle graphics window before trying to use the keyboard. You need to make the turtle window the active listener by clicking on it, then it should respond to the keyboard. If your keystrokes are showing up in the console window instead, this is likely the case.
Another possibility, given your code doesn't end with a mainloop()
, or equivalent, is you're running under an environment like IDLE that you failed to mention which may be affecting your keyboard input events.
Upvotes: 0