問題描述
我使用 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_()`?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!