我将一个 PyQt 示例从 Web 复制到一个文件中,并在 PyCharm 中打开它。下面是代码:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from math import *
class Calculator(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.browser = QTextBrowser()
self.expression = QLineEdit()
self.expression.setPlaceholderText("Type an expression and press Enter.")
self.expression.selectAll()
layout = QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.expression)
self.someWidget = QWidget()
self.someWidget.setLayout(layout)
self.setCentralWidget(self.someWidget)
self.expression.setFocus()
self.expression.returnPressed.connect(self.updateUi)
self.setWindowTitle("Calculator")
def updateUi(self):
try:
text = self.expression.text()
self.browser.append("%s = %s", (text, eval(text)))
except:
self.browser.append("<font color=red>Invalid Expression</font>")
def main():
import sys
app = QApplication(sys.argv)
window = Calculator()
window.show()
sys.exit(app.exec_())
main()
问题在于,即使不添加以下导入语句,代码也能正常运行:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from math import *
我在许多视频和书籍中都看到过这个示例。如果代码在没有上述语句的情况下也能正常工作,那么示例的作者为什么要编写这些语句。
最佳答案
从 PyQt4 到 PyQt5,很多东西都从 QtGui
、QtCore
转移到 QtWidgets
。要在 PyQt5 中编写简单的应用程序,您可能只需要 QtWidgets
。
我的猜测是该代码最初是为 PyQt4 编写的,并“适应”了 PyQt5,没有删除无用的导入。
正确的导入方法是将 PyQt5.QtWidgets 导入为 QtWidgets
(请参阅 Should wildcard import be avoided ? )。
代码变为:
class Calculator(QtWidgets.MainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.browser = QtWidgets.QTextBrowser()
self.expression = QtWidgets.QLineEdit()
...
关于python - 当没有必要时,为什么要在 PyQt 中导入 QtGui 和 QtCore?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33822350/