python - 怎么修错误?
问题描述
我不知道为什么我会得到属性错误。我的代码看起来很干净。我正在使用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() ```
解决方案
首先,如果您很难弄清楚错误是什么,请确保将其包含在错误消息中。我将其编辑为如下所示,并获得了更详细的回溯:
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 问题。之后似乎还有另一个问题,但它似乎与原始问题无关。
推荐阅读
- python - response.xpath().extract_first() 方法的问题
- java - How do I get the character before a specific character with regex?
- haskell - LiquidHaskell 在“Data.String”类型上运行良好但在“Data.Text”类型上运行良好的简单案例
- lotus-notes - Lotus Sametime Embedded - 窗口格式
- python - 将部分函数调用保存在 json 文件中
- python - 我是在 dataset.repeat() dataset.batch() 和 dataset.prefetch() 之前还是之后缓存数据集?
- java - 保存无线电组 onSavedInstance
- django - /course/expression-regular-django/ 'ContactCourses' 对象的 AttributeError 没有属性 'name'
- ruby-on-rails - Ice Cube 如何为每次发生设置持续时间
- python - 如何更改帧分辨率opencv python