JavaScript
x
40
40
1
from PyQt5 import uic
2
from PyQt5.QtCore import *
3
from PyQt5.QtGui import *
4
from PyQt5.QtWidgets import *
5
6
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
7
app = QApplication([])
8
window = uic.loadUi("exercise2.ui")
9
10
11
class Car:
12
def __init__(self):
13
self.speed = 5
14
15
def accelerate(self):
16
if self.speed + 5 < 20:
17
self.speed += 5
18
return self.speed
19
20
def decelerate(self):
21
if self.speed - 5 >= 0:
22
self.speed -= 5
23
return self.speed
24
25
def animate(self):
26
currentX = window.car.x()
27
window.car.setGeometry(currentX + self.speed, 30, 120, 70)
28
29
30
movingCar = Car()
31
timer = QTimer()
32
timer.timeout.connect(movingCar.animate)
33
timer.start(40)
34
35
window.accelerateButton.clicked.connect(Car.accelerate)
36
window.brakeButton.clicked.connect(Car.decelerate)
37
38
window.show()
39
app.exec_()
40
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
:
JavaScript
1
3
1
window.accelerateButton.clicked.connect(movingCar.accelerate)
2
window.brakeButton.clicked.connect(movingCar.decelerate)
3