Matplotlib如何为像Qt这样的后端库设置事件循环,同时仍然允许通过Python REPL进行交互?至少对于Qt,主事件循环必须在主线程中运行,但那就是REPL所在的位置,因此我很难看到两者如何共存。
我目前的尝试是在一个单独的Python
我目前的尝试是在一个单独的Python
threading.Thread
中启动QApplication。def mainloop():
app = QtWidgets.QApplication([])
while True:
app.processEvents()
time.sleep(0.01)
t = threading.Thread(target=mainloop)
t.daemon = True
t.start()
这种方法有点可行,但我会收到一个警告,并且它有时会崩溃:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QApplication(0x7fc5cc001820), parent's thread is QThread(0x7fc5cc001a40), current thread is QThread(0x2702160)
更新 1
以下是使用 QThread
的尝试:
from PyQt5 import QtGui, QtCore, QtWidgets
import time
class Mainloop(QtCore.QObject):
def __init__(self):
super().__init__()
self.app = QtWidgets.QApplication([])
def run(self):
while True:
self.app.processEvents()
time.sleep(1)
t = QtCore.QThread()
m = Mainloop()
m.moveToThread(t)
t.started.connect(m.run)
t.start()
# Essentially I want to be able to interactively build a GUI here
dialog = QtWidgets.QDialog()
dialog.show()
更新2
基本上,我想要仿照下面的交互式Python会话,也就是不运行它作为脚本来呈现一个准备好的GUI。是什么神奇的方法让图形窗口的外观不会阻塞Python解释器呢?
Python 2.7.13 (default, Jan 19 2017, 14:48:08)
Type "copyright", "credits" or "license" for more information.
IPython 5.2.2 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import matplotlib.pyplot as plt
In [2]: plt.ion()
In [3]: fig = plt.figure()
In [4]: # The last command opens a figure window which remains responsive.
...: I can resize it and the window redraws, yet I can still interact
...: with the python interpreter and interactively add new content to t
...: he figure
In [5]: ax = fig.add_subplot(111)
In [6]: # The last command updated the figure window and I can still inter
...: act with the interpreter
In [7]:
app.exec_()
的不同版本。不确定是否有什么误解。我没有使用app.exec_()
的原因是它会在Qt主事件循环中阻塞Python REPL。您能解释一下为什么这样做会起作用吗? - Thomas