【问题标题】:How do I exit a while loop in python with an event?python - 如何在带有事件的python中退出while循环?
【发布时间】:2016-12-14 01:32:26
【问题描述】:

我正在为学校制作这个项目,该项目涉及向树莓派显示数据。我正在使用的代码刷新(并且需要刷新)非常快,但我需要一种让用户停止输出的方法,我认为这需要某种关键事件。问题是,我是 Python 新手,我不知道如何使用 turtle.onkey() 退出 while 循环。我找到了这段代码:

import turtle

def quit():
    global more
    more = False

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

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

这不起作用。我已经测试过了。我该如何进行这项工作,或者是否有其他方法可以在不中断程序流程的情况下获取用户输入?

【问题讨论】:

    标签: python turtle-graphics


    【解决方案1】:

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

    import threading
    
    def something(): 
        while more:
            print("something")
    
    th = threading.Thread(something)
    th.start()
    

    【讨论】:

      【解决方案2】:

      避免 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()),以使所有事件处理程序有机会执行。一些无限循环允许事件触发,但它们通常会调用海龟方法,允许它在某些时候进行控制,但仍然是错误的方法。

      【讨论】:

        【解决方案3】:

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

        在这里,我发现了一个试图将 turtle 引入 IPython 的项目:https://github.com/Andrewkind/Turtle-Ipython。我没有对其进行测试,我不确定这是否比简单地使用不加糖的 shell 更好。

        【讨论】:

          【解决方案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()
          

          【讨论】:

          • 您的回答仍然与OP的问题无关。
          猜你喜欢
          • 2013-05-15
          • 2015-08-15
          • 1970-01-01
          • 2016-08-13
          • 2022-06-12
          • 2022-07-12
          • 1970-01-01
          • 2020-11-05
          • 1970-01-01
          相关资源
          最近更新 更多