PROMPT :
python tkinter two wheels with circle aligned and 4 stokes rotate moving forward and text="SMA INFORMATIKA CIAMIS" attach to them
python
import tkinter as tk
import math
class RollingWheels:
def __init__(self, root):
self.root = root
self.canvas = tk.Canvas(root, width=800, height=200, bg='white')
self.canvas.pack()
# Wheel parameters
self.radius = 40
self.wheel_y = 100
self.x1, self.x2 = 100, 300
self.angle = 0
self.speed = 2
# Create wheels and spokes
self.wheel1 = self.draw_wheel(self.x1, self.wheel_y, self.radius)
self.wheel2 = self.draw_wheel(self.x2, self.wheel_y, self.radius)
# Add text tag
self.text_id = self.canvas.create_text(
200, self.wheel_y - self.radius - 20,
text="SMA INFORMATIKA CIAMIS", font=("Arial", 16, "bold"), fill="blue"
)
self.animate()
def draw_wheel(self, x, y, r):
# Create a group (tag) for the wheel components
tag = f"wheel_{x}"
# Outer circle
self.canvas.create_oval(x-r, y-r, x+r, y+r, width=3, tags=tag)
# 4 Spokes
for i in range(4):
self.canvas.create_line(x, y, x, y, width=2, tags=(tag, "spoke"))
return tag
def animate(self):
self.angle += 0.1
# Update positions
self.x1 += self.speed
self.x2 += self.speed
# Loop if goes off screen
if self.x1 - self.radius > 800: self.x1 = -self.radius
if self.x2 - self.radius > 800: self.x2 = -self.radius
# Move wheel items
for wheel, x_pos in [(self.wheel1, self.x1), (self.wheel2, self.x2)]:
# Clear previous spokes
self.canvas.delete(wheel + "_spoke")
# Redraw spokes rotated
for i in range(4):
a = self.angle + (i * math.pi / 2)
self.canvas.create_line(
x_pos, self.wheel_y,
x_pos + self.radius * math.cos(a),
self.wheel_y + self.radius * math.sin(a),
width=2, tags=(wheel, wheel + "_spoke")
)
# Move outer circle
self.canvas.coords(wheel, x_pos-self.radius, self.wheel_y-self.radius,
x_pos+self.radius, self.wheel_y+self.radius)
# Move text with wheels
self.canvas.coords(self.text_id, (self.x1+self.x2)/2, self.wheel_y - self.radius - 20)
self.root.after(20, self.animate)
root = tk.Tk()
root.title("Rotating Moving Wheels")
app = RollingWheels(root)
root.mainloop()
Key Features:
- Canvas API: Uses
create_oval,create_line, andcreate_text. - Rotation: Calculates spoke positions using
math.cos()andmath.sin(). - Movement: Updates
xcoordinates and moves items withcanvas.coords(). - Animation: Uses
root.after()for a smooth loop

Tidak ada komentar:
Posting Komentar