首页 > 解决方案 > 调用对象类的方法时出现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'”。有人可以帮我弄清楚出了什么问题吗?谢谢!

标签: pythonclassobjectattributes

解决方案


您应该传递给clicked.connect绑定到相关对象的方法,而不是未绑定的方法Car.accelerate

window.accelerateButton.clicked.connect(movingCar.accelerate)
window.brakeButton.clicked.connect(movingCar.decelerate)

推荐阅读