import tkinter as tk
from PIL import Image, ImageTk
import math, os
# 畫布與圓形參數
WIDTH, HEIGHT = 600, 600
RADIUS = 200
CENTER_X, CENTER_Y = WIDTH // 2, HEIGHT // 2
ANGLE_STEP = 2 # 每次旋轉角度
# 建立視窗
root = tk.Tk()
root.title("12 車艙繞圓移動 + 中心連線 + 腳架")
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="white")
canvas.pack()
# ✅ 加上整個摩天輪的支撐腳架(靜態)
foot_base_y = HEIGHT - 50
foot_width = 120
canvas.create_line(CENTER_X, CENTER_Y, CENTER_X - foot_width, foot_base_y, width=6, fill='black')
canvas.create_line(CENTER_X, CENTER_Y, CENTER_X + foot_width, foot_base_y, width=6, fill='black')
canvas.create_line(CENTER_X - foot_width - 50, foot_base_y,
CENTER_X + foot_width + 50, foot_base_y,
fill='gray', dash=(4, 4)) # 地面線
# 載入 6 張圖片
photos = []
for i in range(12):
img_path = os.path.join("unit", f"unit{i%7}.png")
img = Image.open(img_path).resize((40, 60))
photo = ImageTk.PhotoImage(img)
photos.append(photo)
# 建立 6 台車艙,每台車對應一條中心線 + 腳架
cars = []
for i in range(12):
angle = i * 30
rad = math.radians(angle)
x = CENTER_X + RADIUS * math.cos(rad)
y = CENTER_Y + RADIUS * math.sin(rad)
car_id = canvas.create_image(x, y, image=photos[i])
line_id = canvas.create_line(CENTER_X, CENTER_Y, x, y, fill='gray', dash=(4, 2)) # 中心連線
# 加入左右腳架線(初始位置)
foot_offset = 20
leg1 = canvas.create_line(x, y, x - foot_offset, y + foot_offset, fill='black')
leg2 = canvas.create_line(x, y, x + foot_offset, y + foot_offset, fill='black')
cars.append({
'id': car_id,
'angle': angle,
'photo': photos[i],
'line': line_id,
'leg1': leg1,
'leg2': leg2
})
# 動畫更新函數
def move_cars():
for car in cars:
car['angle'] = (car['angle'] + ANGLE_STEP) % 360
rad = math.radians(car['angle'])
x = CENTER_X + RADIUS * math.cos(rad)
y = CENTER_Y + RADIUS * math.sin(rad)
# 更新車艙位置
canvas.coords(car['id'], x, y)
# 更新中心連線
canvas.coords(car['line'], CENTER_X, CENTER_Y, x, y)
# 更新腳架線(左右分叉)
foot_offset = 20
canvas.coords(car['leg1'], x, y, x - foot_offset, y + foot_offset)
canvas.coords(car['leg2'], x, y, x + foot_offset, y + foot_offset)
canvas.after(30, move_cars)
move_cars()
root.mainloop()
沒有留言:
張貼留言