简体   繁体   English

Python 2.7乌龟onkey事件导致循环?

[英]Python 2.7 turtle onkey event causing a loop?

from turtle import *
def PleaseStop():
 SomeWord = input("Which word?")
Screen().onkey(PleaseStop,"a")
Screen().listen()

Pressing "a" will make the program ask "Which word?" 按下“ a”将使程序询问“哪个字?” forever. 永远。

No way to stop it besides closing the program. 除了关闭程序外,没有其他方法可以停止它。 How do I get onkey to call the function only once? 如何让onkey仅调用一次函数?

You need to remove the event bindings by calling onkey with None as first parameter : 您需要通过使用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()

Doesn't solve the problem. 无法解决问题。 Print is fine either way, input() is repeating itself forever, even with none. 无论哪种方式,打印都很好,input()会永远重复自身,即使没有重复也是如此。

I believe @Acorn was heading in the right direction with this but the example provided is incomplete. 我相信@Acorn朝着正确的方向前进,但提供的示例并不完整。 Here's what I feel is a more complete solution: 我觉得这是一个更完整的解决方案:

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

Note that this approach is awkward, clicking the turtle graphics window to make it active, hitting 'a', going back to the console window to type your word. 请注意,此方法很尴尬,单击“乌龟图形”窗口使其处于活动状态,然后单击“ a”,然后返回到控制台窗口以键入您的单词。 If/when you move to Python 3, you can use the turtle function textinput() to prompt for text from the user without having to use input() from the console. 如果/当您使用Python 3时,可以使用乌龟函数textinput()提示用户input()文本,而不必从控制台使用input()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM