代码:
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()
效果:

总结
到此这篇关于如何用python绘制简易动态圣诞树的文章就介绍到这了,更多相关python绘制动态圣诞树内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论