import tkinter as tk
import math
class AnimatedTrain:
def __init__(self, root):
self.root = root
self.root.title("Animated Train")
# Canvas Setup
self.canvas = tk.Canvas(root, width=800, height=300, bg='white')
self.canvas.pack()
# Button
self.btn = tk.Button(root, text="Start Train", command=self.start_animation)
self.btn.pack()
# Initial positions
self.x_pos = 50
self.y_base = 200
self.train_items = []
self.running = False
self.angle = 0
def draw_wagon(self, x, y):
# Wagon body
wagon = self.canvas.create_rectangle(x, y, x+100, y+50, fill='blue',
outline='black')
# 4 Boxes
box1 = self.canvas.create_rectangle(x+5, y+5, x+25, y+25, fill='brown')
box2 = self.canvas.create_rectangle(x+30, y+5, x+50, y+25, fill='brown')
box3 = self.canvas.create_rectangle(x+55, y+5, x+75, y+25, fill='brown')
box4 = self.canvas.create_rectangle(x+80, y+5, x+95, y+25, fill='brown')
# Wheels
wheel1 = self.draw_wheel(x+20, y+50)
wheel2 = self.draw_wheel(x+80, y+50)
return [wagon, box1, box2, box3, box4] + wheel1 + wheel2
def draw_wheel(self, x, y):
radius = 15
wheel = self.canvas.create_oval(x-radius, y-radius, x+radius, y+radius,
fill='black')
spokes = []
for i in range(10):
angle = math.radians(i * 36 + self.angle)
spokes.append(self.canvas.create_line(x, y,
x + radius * math.cos(angle),
y + radius * math.sin(angle), fill='white'))
return [wheel] + spokes
def start_animation(self):
if not self.running:
self.running = True
self.animate()
self.btn.config(state=tk.DISABLED)
def animate(self):
if self.x_pos > 800:
self.x_pos = -200 # Reset position
# Delete old items
for item in self.train_items:
self.canvas.delete(item)
self.train_items = []
# Draw New
self.train_items.extend(self.draw_wagon(self.x_pos, self.y_base))
self.train_items.extend(self.draw_wagon(self.x_pos+110, self.y_base))
# Move & Rotate
self.x_pos += 5
self.angle += 10
if self.running:
self.root.after(50, self.animate)
if __name__ == "__main__":
root = tk.Tk()
app = AnimatedTrain(root)
root.mainloop()

Tidak ada komentar:
Posting Komentar