python - 调用对象类的方法时出现attributeError
问题描述
from PyQt5 import uic
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
app = QApplication([])
window = uic.loadUi("exercise2.ui")
class Car:
def __init__(self):
self.speed = 5
def accelerate(self):
if self.speed + 5 < 20:
self.speed += 5
return self.speed
def decelerate(self):
if self.speed - 5 >= 0:
self.speed -= 5
return self.speed
def animate(self):
currentX = window.car.x()
window.car.setGeometry(currentX + self.speed, 30, 120, 70)
movingCar = Car()
timer = QTimer()
timer.timeout.connect(movingCar.animate)
timer.start(40)
window.accelerateButton.clicked.connect(Car.accelerate)
window.brakeButton.clicked.connect(Car.decelerate)
window.show()
app.exec_()
试图用按钮为汽车设置动画以加速和减速。当我按下一个按钮来加速/减速时,我在两种方法的“if”语句中都得到一个错误“AttributeError:'bool'对象没有属性'speed'”。有人可以帮我弄清楚出了什么问题吗?谢谢!
解决方案
您应该传递给clicked.connect
绑定到相关对象的方法,而不是未绑定的方法Car.accelerate
:
window.accelerateButton.clicked.connect(movingCar.accelerate)
window.brakeButton.clicked.connect(movingCar.decelerate)
推荐阅读
- ios - 在 crashlitycs 中更改捆绑包 ID 的问题
- javascript - 如何在使用 jquery ajax 成功后停止递增存储数组?
- dataset - 结果显示在 Google DATASET 搜索中需要多长时间?
- python - 选择性分组,np.where Pandas/Python 查询
- java - 如何在java中为方法添加参数
- python-3.x - 在命令行中执行多个 python 文件
- android - 如何调用选项卡式活动中片段结果的显式意图?
- javascript - 滑块中的分页,Jquery
- javascript - 执行算术运算后对象属性不返回值
- java - 从 @MvcTest 注释测试调用时,Spring Boot Controller 的行为不同