如何使用事件退出python中的while循环?

如何使用事件退出python中的while循环?,python,turtle-graphics,Python,Turtle Graphics,我正在为学校做这个项目,包括向树莓圆周率显示数据。我正在使用的代码刷新(并且需要刷新)非常快,但我需要一种方法让用户停止输出,我相信这需要某种关键事件。问题是,我是Python新手,不知道如何使用turtle.onkey()退出while循环。我发现这个代码: import turtle def quit(): global more more = False turtle.onkey(quit, "Up") turtle.listen() more = True whil

我正在为学校做这个项目,包括向树莓圆周率显示数据。我正在使用的代码刷新(并且需要刷新)非常快,但我需要一种方法让用户停止输出,我相信这需要某种关键事件。问题是,我是Python新手,不知道如何使用turtle.onkey()退出while循环。我发现这个代码:

import turtle

def quit():
    global more
    more = False

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

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

这不管用。我已经测试过了。我如何做到这一点,或者是否有其他方法可以在不中断程序流程的情况下获取用户输入?

您可以让您循环检查以下文件:

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

您可能正在尝试在交互式IPython shell中运行代码。这是行不通的。不过,裸Python repl shell可以工作

在这里,我发现了一个试图将海龟带到IPython的项目:。我没有对它进行测试,我也不确定这是否是一个比简单地使用未加修饰的shell更好的解决方案。

while循环在线程上运行 检查此代码

import threading

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

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

避免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键上添加了一个restart,这样你就可以再次启动它们。控件应始终到达
mainloop()
(或
done()
exitonclick()
)以使所有事件处理程序都有机会执行。一些无限循环允许事件触发,但它们通常会调用海龟方法,使其能够控制一些时间,但仍然是错误的方法。

您的答案仍然与OP的问题无关。