按Ok按钮将运行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_())
答案 0 :(得分: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)