Should I use `app.exec()` or `app.exec_()` in my PyQt application?(我应该在我的 PyQt 应用程序中使用 `app.exec()` 还是 `app.exec_()`?)
问题描述
我使用 Python 3 和 PyQt5.这是我的测试 PyQt5 程序,关注最后两行:
I use Python 3 and PyQt5. Here's my test PyQt5 program, focus on the last 2 lines:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class window(QWidget):
def __init__(self,parent=None):
super().__init__(parent)
self.setWindowTitle('test')
self.resize(250,200)
app=QApplication(sys.argv)
w=window()
w.show()
sys.exit(app.exec())
#sys.exit(app.exec_())
我知道 exec
是 Python 中的语言关键字.但是 Official PyQt5 Documentation 上的代码(特别是 Object Destruction on Exit 部分).我看到该示例显示了 app.exec()
的使用,这让我感到困惑.
I know exec
is a language keyword in Python. But code on Official PyQt5 Documentation (specifically the Object Destruction on Exit part). I see that example shows use of app.exec()
which confuses me.
当我在我的机器上测试它时.我发现与我的结局没有任何明显的区别.使用和不使用 _
都会在没有时间差的情况下产生相同的输出.
When I tested it on my machine. I found there is no any visible difference from my end. Both with and without _
produces the same output in no time difference.
我的问题是:
- 我使用
app.exec()
有什么问题吗?喜欢与 Python 的内部exec
冲突?我怀疑是因为两个exec
都在执行某些东西. - 如果不能,我可以同时使用两者吗?
- Is there anything wrong going when I use
app.exec()
? like clashing with Python's internalexec
? I suspect because bothexec
's are executing something. - If not, can I use both interchangeably?
推荐答案
那是因为在 Python 3 之前,exec
是一个保留关键字,因此 PyQt 开发人员为其添加了下划线.从 Python 3 开始,exec
不再是保留关键字(因为它是一个内置函数;与 print
的情况相同),所以在 PyQt5 中提供一个不带下划线的版本以与 C++ 文档保持一致是有意义的,但保留一个带下划线的版本是为了向后兼容.所以对于带有 Python 3 的 PyQt5,这两个 exec
函数是相同的.对于较旧的 PyQt,只有 exec_()
可用.
That's because until Python 3, exec
was a reserved keyword, so the PyQt devs added underscore to it. From Python 3 onwards, exec
is no longer a reserved keyword (because it is a builtin function; same situation as print
), so it made sense in PyQt5 to provide a version without an underscore to be consistent with C++ docs, but keep a version with underscore for backwards compatibility. So for PyQt5 with Python 3, the two exec
functions are the same. For older PyQt, only exec_()
is available.
这篇关于我应该在我的 PyQt 应用程序中使用 `app.exec()` 还是 `app.exec_()`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我应该在我的 PyQt 应用程序中使用 `app.exec()` 还是 `app.exec_()`?


基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01