Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7.13 turtle onkey函数不起作用_Python_Python 2.7_Turtle Graphics - Fatal编程技术网

Python 2.7.13 turtle onkey函数不起作用

Python 2.7.13 turtle onkey函数不起作用,python,python-2.7,turtle-graphics,Python,Python 2.7,Turtle Graphics,我制作了一个程序,我想在其中使用onkey()函数,但它不起作用,就像我键盘上的任何键都不起作用一样: 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():

我制作了一个程序,我想在其中使用
onkey()
函数,但它不起作用,就像我键盘上的任何键都不起作用一样:

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()

除了缺少一个
image
变量外,您的代码在Python 2.7.10下对我有效——我对您的代码进行了返工:

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()

一种可能性是,在尝试使用键盘之前,您没有单击海龟图形窗口。您需要通过单击海龟窗口使其成为活动的侦听器,然后它应该响应键盘。如果您的击键显示在控制台窗口中,则可能是这种情况


另一种可能性是,如果您的代码不是以
mainloop()
或等效代码结尾,那么您运行的环境是空闲的,您没有提到这可能会影响您的键盘输入事件。

非常感谢,先生/妈妈,它现在可以工作了。我和我的老师花了这么长时间来研究它,因为我朋友的笔记本电脑也是如此。但我很高兴它能起作用,再次感谢。