代码:
import random
import time
from math import pi, cos, sin
from tkinter import *
CANVAS_WIDTH = 640 # 画布的宽
CANVAS_HEIGHT = 640 # 画布的高
TREE_COLOR = "#2e8b57" # 树的颜色
TRUNK_COLOR = "#8b4513" # 树干的颜色
STAR_COLOR = "#ffff00" # 星星的颜色
LIGHT_COLOR = "#ff4500" # 灯光的颜色
BACKGROUND_COLOR = "#000000" # 背景颜色
TEXT_COLOR = "#ffffff" # 文字颜色
TEXT_FONT = ('Arial', 24, 'bold') # 文字的字体
# 圣诞树的大小和位置
TREE_BOTTOM = CANVAS_HEIGHT - 50
TREE_TOP = TREE_BOTTOM - 200
TREE_WIDTH = 200
TRUNK_WIDTH = 40
TRUNK_HEIGHT = 50
def draw_tree(canvas):
# 树的底部三角形部分
canvas.create_polygon(
CANVAS_WIDTH // 2, TREE_TOP, # 顶部
CANVAS_WIDTH // 2 - TREE_WIDTH, TREE_BOTTOM, # 左下角
CANVAS_WIDTH // 2 + TREE_WIDTH, TREE_BOTTOM, # 右下角
fill=TREE_COLOR, outline="green", width=2
)
# 树的中部三角形部分
canvas.create_polygon(
CANVAS_WIDTH // 2, TREE_TOP + 40, # 顶部
CANVAS_WIDTH // 2 - TREE_WIDTH * 0.8, TREE_BOTTOM - 40, # 左下角
CANVAS_WIDTH // 2 + TREE_WIDTH * 0.8, TREE_BOTTOM - 40, # 右下角
fill=TREE_COLOR, outline="green", width=2
)
# 树的顶部三角形部分
canvas.create_polygon(
CANVAS_WIDTH // 2, TREE_TOP + 80, # 顶部
CANVAS_WIDTH // 2 - TREE_WIDTH * 0.6, TREE_BOTTOM - 80, # 左下角
CANVAS_WIDTH // 2 + TREE_WIDTH * 0.6, TREE_BOTTOM - 80, # 右下角
fill=TREE_COLOR, outline="green", width=2
)
# 树干
canvas.create_rectangle(
CANVAS_WIDTH // 2 - TRUNK_WIDTH // 2, TREE_BOTTOM, # 左上角
CANVAS_WIDTH // 2 + TRUNK_WIDTH // 2, TREE_BOTTOM + TRUNK_HEIGHT, # 右下角
fill=TRUNK_COLOR, outline=TRUNK_COLOR
)
def draw_star(canvas, x, y, size):
# 绘制一个星星
canvas.create_oval(
x - size, y - size, x + size, y + size, # 左上角和右下角
fill=STAR_COLOR, outline=STAR_COLOR
)
def draw_lights(canvas, x, y, size, color):
# 绘制一颗灯泡
canvas.create_oval(
x - size, y - size, x + size, y + size, # 左上角和右下角
fill=color, outline=color
)
def draw_dynamic_star(canvas, frame):
# 让星星闪烁
if frame % 30 < 15:
draw_star(canvas, CANVAS_WIDTH // 2, TREE_TOP - 40, 15)
def draw_dynamic_lights(canvas, frame):
# 动态灯泡
num_lights = 15
for i in range(num_lights):
angle = 2 * pi * i / num_lights # 每个灯泡的位置角度
x = CANVAS_WIDTH // 2 + (TREE_WIDTH * 0.6) * cos(angle)
y = TREE_TOP + 80 + (TREE_WIDTH * 0.6) * sin(angle)
# 每个灯泡随机闪烁
color = LIGHT_COLOR if random.random() > 0.5 else "black"
draw_lights(canvas, x, y, 5, color)
def draw_text(canvas):
# 显示圣诞祝福
canvas.create_text(CANVAS_WIDTH // 2, CANVAS_HEIGHT - 20, text="Merry Christmas!", fill=TEXT_COLOR, font=TEXT_FONT)
def draw_dynamic_tree(main, canvas, frame):
# 清空画布
canvas.delete('all')
# 绘制圣诞树
draw_tree(canvas)
# 绘制闪烁的星星
draw_dynamic_star(canvas, frame)
# 绘制动态灯光
draw_dynamic_lights(canvas, frame)
# 绘制祝福语
draw_text(canvas)
# 设置每帧调用
main.after(100, draw_dynamic_tree, main, canvas, frame + 1)
if __name__ == '__main__':
root = Tk() # 创建一个Tk对象
canvas = Canvas(root, bg=BACKGROUND_COLOR, height=CANVAS_HEIGHT, width=CANVAS_WIDTH)
canvas.pack()
# 动态绘制圣诞树
draw_dynamic_tree(root, canvas, 0)
# 启动应用
root.mainloop()
效果: