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_()
Trying to animate a car with button to accelerate and decelerate. When I press a button to accelerate/decelerate, I get an error in the ‘if’ statements on both methods “AttributeError: ‘bool’ object has no attribute ‘speed'”. Can someone help me figure out what’s going wrong? Thank you!
Advertisement
Answer
You should pass to clicked.connect a method bound to the object in question instead of the unbound method Car.accelerate:
window.accelerateButton.clicked.connect(movingCar.accelerate) window.brakeButton.clicked.connect(movingCar.decelerate)