I am working on a homework problem for my Python course that is supposed to display a car (got that) and then the car is supposed to simulate driving across the window until it reaches the end, and then restarting at the beginning. I have a race function that is supposed to be doing this but it's not doing anything. I'm having a hell of a time with classes and tkinter. I know that I need the value of x to be incremented each time it loops and updates so that the car looks like its moving, I'm just not sure how to implement that. Is my boolean not written correctly? I've tried changing things around a few different ways with the function but I can't seem to get it to do anything, so I must be missing something.
UPDATE: I have moved the race method into the class, and called it within the constructor. I put a print statement to get the value of x in the race method and its showing that x is being incremented correctly, but when I run the program my car disappears. So it's updating the value of x as it should, but its not displaying the graphic. Code updated below
Any suggestions are appreciated!
# Import tkinter
from tkinter import *
# Set the height and Width of the window
width = 800
height = 800
# Create race car class with canvas as the argument
class RacingCar(Canvas):
# Constructor
def __init__(self, master, width, height):
# Constructor
Canvas.__init__(self, master, width = width, height = height)
# Create x and y variables for starting position
self.x = 10
self.y = 40
# Display the car
self.display_car()
self.race()
# Function to display car
def display_car(self):
# Delete original car
self.delete("car")
# Create first wheel
self.create_oval(self.x + 10, self.y - 10, self.x + 20,\
self.y, fill = "black", tags = "car")
# Create the second wheel
self.create_oval(self.x + 30, self.y - 10, self.x + 40,\
self.y, fill = "black", tags = "car")
# Create the body
self.create_rectangle(self.x, self.y - 20, self.x + 50,\
self.y - 10, fill = "green", tags = "car")
# Create the roof
self.create_polygon(self.x + 10, self.y - 20, self.x + 20,\
self.y - 30, self.x + 30, self.y - 30,\
self.x + 40, self.y - 20, fill = "green",\
tags = "car")
def race():
while True:
if self.x < width:
self.x += 2
else:
self.x = 0
self.after(88)
self.update()
window = Tk()
window.title("Racing Car")
racecar = RacingCar(window, width = 240, height = 50 )
racecar.pack()
window.mainloop()