[英]Python 2.7 turtle onkey event causing a loop?
from turtle import *
def PleaseStop():
SomeWord = input("Which word?")
Screen().onkey(PleaseStop,"a")
Screen().listen()
按下“ a”将使程序询问“哪个字?” 永远。
除了关闭程序外,没有其他方法可以停止它。 如何让onkey
仅调用一次函数?
您需要通过使用None
作为第一个参数的onkey
来删除事件绑定:
import turtle
def OnKeyA():
print 'Key "a" was pressed'
turtle.Screen().onkey(None, 'a')
turtle.Screen().onkey(OnKeyA, 'a')
turtle.Screen().listen()
turtle.mainloop()
无法解决问题。 无论哪种方式,打印都很好,input()会永远重复自身,即使没有重复也是如此。
我相信@Acorn朝着正确的方向前进,但提供的示例并不完整。 我觉得这是一个更完整的解决方案:
from turtle import Turtle, Screen, mainloop
def OnKeyA():
screen.onkey(None, 'a')
some_word = raw_input("Which word? ")
turtle.write(some_word, font=('Arial', 18, 'normal'))
screen = Screen()
turtle = Turtle()
screen.onkey(OnKeyA, 'a')
print("Click on turtle window to make it active, then type 'a'")
screen.listen()
mainloop()
请注意,此方法很尴尬,单击“乌龟图形”窗口使其处于活动状态,然后单击“ a”,然后返回到控制台窗口以键入您的单词。 如果/当您使用Python 3时,可以使用乌龟函数textinput()
提示用户input()
文本,而不必从控制台使用input()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.