我将一个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()
问题是即使不添加以下import语句,代码也能正常运行:
^{pr2}$我在很多视频和书籍中看到过这个例子。如果没有上述语句,代码可以正常工作,那么为什么示例作者要编写这些语句。在
从PyQt4到PyQt5,很多东西从}。要在PyQt5中编写一个简单的应用程序,您可能只需要
QtGui
,QtCore
转移到{QtWidgets
。在我的猜测是,代码最初是为PyQt4编写的,并且“改编”为PyQt5,而没有删除无用的导入。在
正确的导入方法是
import PyQt5.QtWidgets as QtWidgets
(请参见Should wildcard import be avoided ?)。在然后代码变成:
相关问题 更多 >
编程相关推荐