2016-12-14 50 views
0

我正在为涉及向树莓派显示数据的学校开展此项目。我正在使用的代码非常快速刷新(并需要刷新),但我需要一种让用户停止输出的方式,我相信这需要某种关键事件。事情是,我是Python的新手,我无法弄清楚如何使用turtle.onkey()退出while循环。我发现这个代码:如何在python中使用事件退出while循环?

import turtle 

def quit(): 
    global more 
    more = False 

turtle.onkey(quit, "Up") 
turtle.listen() 

more = True 
while more: 
    print("something") 

这是行不通的。我测试过了。我该如何做这项工作,或者有另一种方式来获得用户输入而不中断程序的流程?

回答

-4

你可以有你循环检查文件是这样的:

def check_for_value_in_file(): 
    with open('file.txt') as f: 
     value = f.read() 
    return value 

while check_for_value_in_file() == 'the right value': 
    do_stuff() 
+1

这并没有回答这个问题... – Chris

+0

对不起,点击提交一下,我就吸取了教训。 – zemekeneng

+1

你的答案仍然与OP的问题无关。 – kay

0

有机会,你正试图在一个交互式的IPython shell中运行代码。这是行不通的。尽管如此,裸露的Python repl shell仍然有效。

在这里,我找到了一个项目,试图将乌龟带到IPython:https://github.com/Andrewkind/Turtle-Ipython。我没有对它进行测试,我也不确定这是否比简单使用非糖壳更好。

1

而上线 检查循环运行该代码

import threading 

def something(): 
    while more: 
     print("something") 

th = threading.Thread(something) 
th.start() 
0

避免在Python乌龟图形程序的无限循环:

more = True 
while more: 
    print("something") 

可以有效地阻止来自发射活动,包括一个旨在停止循环。相反,使用计时器事件来运行你的代码,并允许其他事件火了:

from turtle import Screen 

more = True 

counter = 0 

def stop(): 
    global more 
    more = False 

def start(): 
    global more 
    more = True 
    screen.ontimer(do_something, 100) 

def do_something(): 
    global counter 
    print("something", counter) 
    counter += 1 

    if more: 
     screen.ontimer(do_something, 100) 

screen = Screen() 

screen.onkey(stop, "Up") 
screen.onkey(start, "Down") 
screen.listen() 

start() 

screen.mainloop() 

我添加了一个计数器,以你的程序只是让你可以更容易地看到,当“东西”语句停止,我已经向下键添加重新启动,以便您可以重新启动它们。控制应始终达到mainloop()(或done()exitonclick()),以使所有事件处理程序有机会执行。一些无限循环允许事件触发,但他们通常会调用乌龟方法,使其能够控制一些时间,但仍然是错误的方法。