PyQt 窗口打开后立即关闭 [英] PyQt window closes immediately after opening
问题描述
我在尝试打开 PyQt 窗口时遇到问题.
I am getting an issue when trying to open a PyQt window.
下面的代码是我的原始代码的一个例子.当我在 import Test
中导入模块并运行 test.Start()
时,出现以下错误:
The code below is an example of my original code. When I imported the module in import Test
and ran test.Start()
, I got the following error:
QCoreApplication::exec:事件循环已经在运行
QCoreApplication::exec: The event loop is already running
经过一番研究,我发现是因为我已经做了一个QApplication
.
After some research, I found out it was because I had already already made a QApplication
.
test.py....
import sys
def Start():
app = QApplication(sys.argv)
m = myWindow()
m.show()
app.exec_()
class myWindow():....
if __name__ == "__main__":
Start()
然后我读到我可以像这样重写我的代码,它会修复错误:
So then I read that I could rewrite my code like this and it would fix the error:
test.py....
def Start():
m = myWindow()
m.show()
class myWindow():....
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
Start()
app.exec_()
现在我不再收到 QCoreApplication::exec: The event loop already running 错误,但我的窗口在打开后几乎立即关闭.
Now I no longer get the QCoreApplication::exec: The event loop is already running error, but my window closes almost immediately after opening.
推荐答案
你需要保留对打开的窗口的引用,否则它会超出范围并被垃圾收集,这也会破坏底层的 C++ 对象.试试:
You need to keep a reference to the opened window, otherwise it goes out of scope and is garbage collected, which will destroy the underlying C++ object also. Try:
def Start():
m = myWindow()
m.show()
return m
class myWindow():....
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
window = Start()
app.exec_()
这篇关于PyQt 窗口打开后立即关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!