简体   繁体   中英

How do I exit a while loop in python with an event?

I'm making this project for school that involves displaying data to a raspberry pi. The code I'm using refreshes (and needs to refresh) incredibly quickly, but I need a way for the user to stop the output, which I believe requires some kind of key event. The thing is, I'm new to Python and I can't figure out how to exit a while loop with turtle.onkey(). I found this code:

import turtle

def quit():
    global more
    more = False

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

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

Which doesn't work. I've tested it. How do I make this work, or is there another way to get user input without interrupting the flow of the program?

while loop run on thread check this code

import threading

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

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

Chances are that you are trying to run your code in an interactive IPython shell. That does not work. The bare Python repl shell works, though.

Here I found a project that tries to bring turtle to IPython: https://github.com/Andrewkind/Turtle-Ipython . I did not test it, and I'm not exactly sure that this is a better solution than simply using the unsugared shell.

Avoid infinite loops in a Python turtle graphics program:

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

You can effectively block events from firing, including the one intended to stop the loop. Instead, use timer events to run your code and allow other events to fire:

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

I've added a counter to your program just so you can more easily see when the 'something' statements stop and I've added a restart on the down key so you can start them up again. Control should always reach mainloop() (or done() or exitonclick() ) to give all the event handlers a chance to execute. Some infinite loops allow events to fire but they typically have calls into the turtle methods that allow it to have control some of the time but are still the wrong approach.

You could have you loop check a file like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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