我正在编写一个 Python 程序,该程序具有使用 PyQt5 的 GUI,并且还使用 os.system() 调用 MATLAB 文件。但是,我的函数之一决定在调用 os.system 之前不执行任何与 PyQt 相关的语句。像“print”这样的普通函数在 os.system 之前运行,但其他函数则不会。但是,它在 os.system 被调用后运行它们就好了
Ex)
def button_clicked(self):
print("Button Clicked") #works
self.label.hide() #does nothing
os.system() #MATLAB called. works
self.label.hide() #now works
我完全不知道为什么会发生这种情况。真正奇怪的是,程序似乎忽略了 os.system 之前函数中与 PyQt 相关的所有内容,因为即使我执行以下操作:
def myFunction(self):
self.label.hide()
self.label2.hide()
print("myFunction Called")
def button_clicked(self):
self.label.hide() #does nothing
self.label2.hide() #does nothing
print("Button Clicked") #works
self.myFunction() #does everything in the function unless it's PyQt-related, in this instance, it prints "myFunction Called" and nothing else
os.system() #MATLAB called. Works
self.label.hide() #now works
self.label2.hide() #now works
os.system 总是在函数或其他东西中首先执行吗?但这并不能解释为什么像“打印”这样的东西会起作用。
os.system()
is blocking。这意味着它不会返回,直到它调用的命令实际返回(例如:程序退出)。
对于像 Qt 这样的事件驱动系统来说,这是一个terrible错误,因为阻塞函数阻止事件循环处理所有事件:不仅是来自系统的事件(例如键盘或鼠标交互),还有它自己的事件,最重要的是drawing小部件。
从 Qt 的角度来看,您的标签实际上是隐藏的(您可以尝试print(self.label.isVisible())
),但既然你打电话os.system
紧接着,Qt 就没有时间去视觉更新小部件以反映这一点。
虽然通常线程(使用 python 自己的模块或 Qt 的 QThread,具体取决于要求,甚至 QRunnable)是潜在阻塞操作的首选,因为您实际上想要启动一个新程序,但最简单的解决方案是使用 QProcess,也许使用它自己的静态方法startDetached() https://doc.qt.io/qt-5/qprocess.html#startDetached-1.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)