import tkinter as tk
import math
# --- Configuration ---
WIDTH, HEIGHT = 800, 300
RECT_W, RECT_H = 150, 60
WHEEL_RADIUS = 25
SPOKE_COLOR = "white"
ROTATION_SPEED = 15
class Vehicle:
def __init__(self, canvas, x, y):
self.canvas = canvas
self.x = x
self.y = y
self.angle = 0
self.speed = 0
# Create components
self.body = self.canvas.create_rectangle(
x, y, x + RECT_W, y + RECT_H, fill="brown", outline="black", width=2)
self.text = self.canvas.create_text(
x + RECT_W/2, y + RECT_H/2, text="Hello", fill="white", font=('Arial', 16, 'bold'))
# Wheels
self.wheel1 = self.create_wheel(x + 30, y + RECT_H)
self.wheel2 = self.create_wheel(x + RECT_W - 30, y + RECT_H)
self.wheels = [self.wheel1, self.wheel2]
def create_wheel(self, cx, cy):
# Circle
circle = self.canvas.create_oval(
cx - WHEEL_RADIUS, cy - WHEEL_RADIUS,
cx + WHEEL_RADIUS, cy + WHEEL_RADIUS, fill="black")
# 4 Spokes
spokes = []
for i in range(4):
spokes.append(self.canvas.create_line(cx, cy, cx, cy, fill=SPOKE_COLOR, width=2))
return {'circle': circle, 'spokes': spokes, 'center': (cx, cy)}
def move(self, direction):
# Update position
self.speed = direction * 10
self.angle += direction * ROTATION_SPEED
self.canvas.move(self.body, self.speed, 0)
self.canvas.move(self.text, self.speed, 0)
for wheel in self.wheels:
self.canvas.move(wheel['circle'], self.speed, 0)
# Rotate Spokes
cx, cy = wheel['center'][0] + self.speed, wheel['center'][1] # This is wrong, needs to track total move
# Properly move and rotate everything
self.update_components()
def update_components(self):
# Update centers based on total movement
self.x += self.speed
# Move wheels and re-calculate spokes
for wheel in self.wheels:
# Re-center spokes based on current wheel position
cx = self.canvas.coords(wheel['circle'])[0] + WHEEL_RADIUS
cy = self.canvas.coords(wheel['circle'])[1] + WHEEL_RADIUS
wheel['center'] = (cx, cy)
for i in range(4):
angle = math.radians(self.angle + (i * 90))
x2 = cx + WHEEL_RADIUS * math.cos(angle)
y2 = cy + WHEEL_RADIUS * math.sin(angle)
self.canvas.coords(wheel['spokes'][i], cx, cy, x2, y2)
# --- Setup ---
root = tk.Tk()
root.title("Moving Vehicle")
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="white")
canvas.pack()
vehicle = Vehicle(canvas, 50, 150)
# --- Controls ---
def left(event): vehicle.move(-1)
def right(event): vehicle.move(1)
root.bind("<Left>", left)
root.bind("<Right>", right)
root.mainloop()



