Python PyQt:如何在不锁定主对话框的情况下运行while循环

2 投票
1 回答
6478 浏览
提问于 2025-04-17 21:52

点击“确定”按钮会运行 while_loop() 方法,这个方法会在屏幕上打印一些信息。

while_loop() 方法在运行时,主对话框就会变得无响应。 有趣的是,即使对话框窗口被关闭,这个函数仍然会继续运行。显然,这并不是我们想要的。当对话框关闭时,while_loop() 方法也应该停止运行。如果能让 while_loop() 方法在运行时不让主对话框无响应,那就太好了……

import sys, time
from PyQt4 import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.main_layout = QtGui.QVBoxLayout()

        ok_button = QtGui.QPushButton("Run")
        ok_button.clicked.connect(self.OK)      
        self.main_layout.addWidget(ok_button)       

        cancel_button = QtGui.QPushButton("Cancel")
        cancel_button.clicked.connect(self.cancel)      
        self.main_layout.addWidget(cancel_button)

        central_widget = QtGui.QWidget()
        central_widget.setLayout(self.main_layout)
        self.setCentralWidget(central_widget)

    def myEvenListener(self):
        state=True
        while state:
            for i in range(10,100):
                time.sleep(i*0.01)
                print '.'*i

    def OK(self):
        self.myEvenListener()       

    def cancel(self):
        sys.exit()  

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.resize(480, 320)
    window.show()
    sys.exit(app.exec_())

1 个回答

2

你可能想用线程来解决这个问题,这样你的线程就可以正常结束了。

import threading
import sys, time
from PyQt4 import QtCore, QtGui
import psutil
import os

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.main_layout = QtGui.QVBoxLayout()

        ok_button = QtGui.QPushButton("Run")
        ok_button.clicked.connect(self.OK)      
        self.main_layout.addWidget(ok_button)       

        cancel_button = QtGui.QPushButton("Cancel")
        cancel_button.clicked.connect(self.cancel)      
        self.main_layout.addWidget(cancel_button)

        central_widget = QtGui.QWidget()
        central_widget.setLayout(self.main_layout)
        self.setCentralWidget(central_widget)

    def myEvenListener(self,stop_event):
        state=True
        while state and not stop_event.isSet():
            for i in range(10,100):
                time.sleep(i*0.01)
                print '.'*i

    def OK(self):
        self.stop_event=threading.Event()
        self.c_thread=threading.Thread(target=self.myEvenListener, args=(self.stop_event,))
        self.c_thread.start()       

    def cancel(self):
        self.stop_event.set()
        self.close()    

def main():
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.resize(480, 320)
    window.show()
    app.exec_()
main()


def kill_proc_tree(pid, including_parent=True):    
    parent = psutil.Process(pid)
    if including_parent:
        parent.kill()

me = os.getpid()
kill_proc_tree(me)

撰写回答