在使用 python 几年后,这是第一次发生在 python 提示符下逐行尝试某些代码与在脚本文件中运行它产生不同结果的情况。
代码很简单:
import os, sys
from PyQt4 import QtGui, QtCore, uic
app = QtGui.QApplication(sys.argv)
splash=QtGui.QSplashScreen(QtGui.QPixmap("/home/pippo/splashscreen.jpg"))
splash.show()
print "hello!"
time.sleep(10)
如果我在 python 提示符(版本 2.7.3)中一行一行地输入 splash.show() 行之后我可以看到屏幕上显示的图像,如果我改为在脚本中运行它 图像未显示,但我可以看到启动后的打印正确地显示在终端上。
任何人都可以帮助我理解这两种不同行为的原因是什么吗?
最佳答案
来自documentation :
PyQt4 installs an input hook (using PyOS_InputHook) that processes events when an interactive interpreter is waiting for user input. This means that you can, for example, create widgets from the Python shell prompt, interact with them, and still being able to enter other Python commands.
至于您的脚本,您必须为 Qt 事件循环调用 app.exec_() 以启动(并显示启动画面)。在 C++ Qt 程序中也会发生同样的情况,如果没有事件循环,您将无法获得任何 GUI。
关于Python 代码在提示中工作,而不是在脚本中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15875785/