Python 代码在提示中工作,而不是在脚本中工作

标签 python command-line pyqt

在使用 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/

相关文章:

java - 让 JVM 根据需要增加内存需求,直到达到 VM 限制的大小?

python - 为什么我的 python 类继承不正确?

python - 带边框半径的 QMovie

python - 如何从 Pandas 数据框中提取列表或字典中的非 NA 值

python - 150x150 图像上的基本 softmax 模型实现

Python - For 循环数百万行

c++ - 无法从 'g++' 调用获得输出结果

c# - 如何使用 FFMPEG 传递参数

c++ - 在 PySide (Qt) 中打开另一个程序并在原始窗口中显示

python - 如何为 argparse 参数提供类型提示?