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 = 1 # 每次旋轉角度
# 建立視窗
root = tk.Tk()
root.title("24 車艙繞圓移動 + 中心連線 + 腳架")
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)) # 地面線
# 載入 24 張圖片
photos = []
for i in range(24):
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)
# 建立 24 台車艙,每台車對應一條中心線 + 腳架
cars = []
for i in range(24):
angle = i * 15
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,
})
# 動畫更新函數
frame = 0 # 全域 frame 計數器
def move_cars():
global frame
frame += ANGLE_STEP # 每次更新一點點角度
x_scale = -0.6 + 0.6 * abs(math.cos(math.radians(frame))) # x 縮放因子:0.6~1.0
for car in cars:
car['angle'] = (car['angle'] + ANGLE_STEP) % 360
rad = math.radians(car['angle'])
# 🚩 加入 x_scale 縮放
x = CENTER_X + RADIUS * math.cos(rad) * x_scale
y = CENTER_Y + RADIUS * math.sin(rad)
# 更新車艙位置
canvas.coords(car['id'], x, y)
# 更新中心連線
canvas.coords(car['line'], CENTER_X, CENTER_Y, x, y)
canvas.after(30, move_cars)
move_cars()
root.mainloop()
沒有留言:
張貼留言