[英]How do I exit a while loop in python with an event?
我正在为学校做这个项目,涉及到向树莓派显示数据。 我正在使用的代码非常快地刷新(并且需要刷新),但是我需要用户停止输出的方法,我认为这需要某种键事件。 问题是,我是Python的新手,我不知道如何使用turtle.onkey()退出while循环。 我发现以下代码:
import turtle
def quit():
global more
more = False
turtle.onkey(quit, "Up")
turtle.listen()
more = True
while more:
print("something")
这不起作用。 我已经测试过了 我如何进行这项工作,或者还有另一种方法可以在不中断程序流程的情况下获取用户输入?
在线程上运行while循环时检查此代码
import threading
def something():
while more:
print("something")
th = threading.Thread(something)
th.start()
您可能会尝试在交互式IPython Shell中运行代码。 那行不通。 不过,裸露的Python repl shell可以工作。
在这里,我找到了一个尝试将乌龟带入IPython的项目: https : //github.com/Andrewkind/Turtle-Ipython 。 我没有对其进行测试,而且我不完全确定这是比仅使用未受污染的外壳更好的解决方案。
在Python turtle图形程序中避免无限循环:
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()
我为您的程序添加了一个计数器,以便您可以更轻松地看到“ something”语句何时停止,并且在down键上添加了重新启动操作,以便您可以再次启动它们。 控件应始终到达mainloop()
(或done()
或exitonclick()
),以使所有事件处理程序都有执行的机会。 一些无限循环允许事件触发,但是它们通常都调用了turtle方法,从而使它在某些时候可以控制,但仍然是错误的方法。
您可以让您循环检查以下文件:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.