How to quit the program in while loop using push-button in PyQt

后端 未结 2 1385
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-19 04:42

I have the following code which will start after clicking the \'Start\' button in PyQt:

def Start(self):
  import time
  import os
  import RPi.GPIO as GPIO
         


        
2条回答
  •  囚心锁ツ
    2021-01-19 05:19

    1. This question is useful: tkinter loop and serial write It could be copied over with two changes: master.update becomes QtGui.qApp.processEvents and master.after becomes QTimer.singleShot.

    2. Here is a sketch of how to do what you ask for with guiLoop:

      from guiLoop import guiLoop, stopLoop
      # ... means fill in your code
      class ...: 
          started = False
      
          def Start(self):
              if not self.started:
                  # you can also use threads here, see the first link
                  self.started = self.StartLoop()
      
          def Stop(self):
              if self.started:
                  stopLoop(self.started)
                  self.started = False
      
          @guiLoop
          def StartLoop(self):
              # This is your Start function
              # ...
              while True:
                  # ...
                  yield 0.085 # time.sleep(0.085) equivalent
                  # ...
      

      Since I do not know what your code look like, here is a working example using PyQT4 and guiLoop:

      from PyQt4 import QtGui
      import sys
      
      from guiLoop import guiLoop # https://gist.github.com/niccokunzmann/8673951
      
      @guiLoop
      def led_blink(argument):
          while 1:
              print("LED on " + argument)
              yield 0.5 # time to wait
              print("LED off " + argument)
              yield 0.5
      
      app = QtGui.QApplication(sys.argv)
      
      w = QtGui.QWidget()
      w.resize(250, 150)
      w.move(300, 300)
      w.setWindowTitle('Simple')
      w.show()
      
      led_blink(w, 'shiny!')
      
      sys.exit(app.exec_())
      

      guiLoop uses QTimer.singleShot(time, function) to make the loop continue.

      You can also stop the loop with stopLoop() of guiLoop.

提交回复
热议问题