错误?,python,attributes"/>

首页 > 解决方案 > 怎么修错误?

问题描述

我不知道为什么我会得到属性错误。我的代码看起来很干净。我正在使用pyqt5。我的 ui 代码链接:ui 代码

我正在尝试制作 ui 计算器。我的空闲:PyCharm 2020

后端代码:

from PyQt5 import QtWidgets
from calculatorui import Ui_MainWindow
import sys
class myApp(QtWidgets.QMainWindow):
    def __init__(self):
        super(myApp, self).__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.btn_bolme.clicked.connect(self.hesapla)
        self.ui.btn_carpma.clicked.connect(self.hesapla)
        self.ui.btn_toplama.clicked.connect(self.hesapla)
        self.ui.btn_cikarma.clicked.connect(self.hesapla)


    def hesapla(self):
        sender=self.sender().text()
        result=0
        try:

            if sender.text()=="Toplama":
                result = int(self.ui.lbl_sayi1.text()) + int(self.ui.lbl_sayi2.text())
            elif sender.text()=="Çıkarma":
                result = int(self.ui.lbl_sayi1.text()) - int(self.ui.lbl_sayi2.text())
            elif sender.text()=="Çarpma":
                result = int(self.ui.lbl_sayi1.text()) * int(self.ui.lbl_sayi2.text())
            elif sender.text()=="Bölme":
                result = int(self.ui.lbl_sayi1.text()) / int(self.ui.lbl_sayi2.text())
            self.ui.txt_sonuc.setText("Sonuç: "+str(result))
        except ZeroDivisionError:
            self.ui.txt_sonuc.setText("0'a bölemezsin")
        except:
            print("Unexpected error:", sys.exc_info()[0])
def app():
    app=QtWidgets.QApplication(sys.argv)
    win=myApp()
    win.show()
    sys.exit(app.exec_())
app() ```

标签: pythonattributes

解决方案


首先,如果您很难弄清楚错误是什么,请确保将其包含在错误消息中。我将其编辑为如下所示,并获得了更详细的回溯:

except Exception as e:
    print(f"Unexpected error:{e}", sys.exc_info()[0])

回溯显示您在哪里遇到属性错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-13-387a1e8e21c9> in hesapla(self)
     81         try:
---> 82             if sender.text()=="Toplama":
     83                 result = int(self.ui.lbl_sayi1.text()) + int(self.ui.lbl_sayi2.text())

AttributeError: 'str' object has no attribute 'text'

仔细检查后,问题似乎出在:

    def hesapla(self):
        sender=self.sender().text() <------!!!
        result=0
        try:
            if sender.text()=="Toplama": <---------!!!
                result = int(self.ui.lbl_sayi1.text()) + int(self.ui.lbl_sayi2.text())

你调用text()on self.sender(),它返回一个字符串。然后,您尝试再次调用text()第一次调用的结果。如果您.text()在第一行hesapla或 if 语句中删除,那应该可以解决您的 AttributeError 问题。之后似乎还有另一个问题,但它似乎与原始问题无关。


推荐阅读