python +t kinter绘制彩虹和云朵
彩虹,简称虹,是气象中的一种光学现象,当太阳光照射到半空中的水滴,光线被折射及反射,在天空上形成拱形的七彩光谱,由外圈至内圈呈红、橙、黄、绿、蓝、靛、紫七种颜色。事实上彩虹有无数种颜色,比如,在红色和橙色之间还有许多种细微差别的颜色,但为了简便起见,所以只用七种颜色作为区别。
先给出运行效果:
源码如下:
import tkinter as tk# 创建主窗口
root = tk.Tk()
root.title("彩虹")
root.geometry("400x300")# 创建画布
canvas = tk.Canvas(root, width=400, height=300, bg="#87CEEB") # 天蓝色背景
canvas.pack()# 绘制彩虹
def draw_rainbow():center_x = 200 # 画布中心 Xcenter_y = 320 # 调整 Y 值使彩虹靠下radius = 240 # 彩虹半径# 彩虹颜色colors = ['#FF0000', # 红'#FF7F00', # 橙'#FFFF00', # 黄'#00FF00', # 绿'#0000FF', # 蓝'#4B0082', # 靛'#9400D3' # 紫]# 绘制彩虹弧线for i in range(len(colors)):canvas.create_arc(center_x - (radius - i * 20), center_y - (radius - i * 20),center_x + (radius - i * 20), center_y + (radius - i * 20),start=0, extent=180, outline=colors[i], width=20, style=tk.ARC)#绘制云朵
def draw_cloud(x, y, size):canvas.create_oval(x, y, x + size *2, y + size, fill="white", outline="white")canvas.create_oval(x + size //2, y - size //2, x + size *2.5, y + size //2, fill="white", outline="white")#绘制彩虹
draw_rainbow()#绘制云朵
draw_cloud(50, 50, 30) #左侧云朵
draw_cloud(250, 80, 25) #右侧云朵#运行主循环
root.mainloop()
下免修改云彩代码,让云彩从左向右不停地移动,先给出运行效果:
源码如下:
import tkinter as tk# 创建主窗口
root = tk.Tk()
root.title("彩虹")
root.geometry("400x300")# 创建画布
canvas = tk.Canvas(root, width=400, height=300, bg="#87CEEB") # 天蓝色背景
canvas.pack()# 绘制彩虹
def draw_rainbow():center_x = 200 # 画布中心 Xcenter_y = 320 # 调整 Y 值使彩虹靠下radius = 240 # 彩虹半径# 彩虹颜色colors = ['#FF0000', # 红'#FF7F00', # 橙'#FFFF00', # 黄'#00FF00', # 绿'#0000FF', # 蓝'#4B0082', # 靛'#9400D3' # 紫]# 绘制彩虹弧线for i in range(len(colors)):canvas.create_arc(center_x - (radius - i *20), center_y - (radius - i *20),center_x + (radius - i *20), center_y + (radius - i *20),start=0, extent=180, outline=colors[i], width=20, style=tk.ARC)#绘制云朵
def draw_cloud(x, y, size):cloud_part1 = canvas.create_oval(x, y, x + size *2, y + size, fill="white", outline="white")cloud_part2 = canvas.create_oval(x + size //2, y - size //2, x + size *2.5, y + size //2, fill="white", outline="white")return [cloud_part1, cloud_part2] #返回两个椭圆的ID列表#云朵移动函数
def move_cloud(cloud_parts, speed):for part in cloud_parts: #遍历云朵的每个部分coords = canvas.coords(part)#如果云朵移出画布右侧边界,则将其重新放置到左侧if coords[2] >400 + 50: canvas.move(part,-450,0) #移动云朵的当前部分canvas.move(part,speed,0)#每隔50毫秒调用一次move_cloud函数,形成动画效果root.after(50,move_cloud,cloud_parts,speed)#绘制彩虹
draw_rainbow()#绘制云朵并获取其ID列表(用于移动)
cloud1 = draw_cloud(50,50,30) #左侧云朵
cloud2 = draw_cloud(250,80,25) #右侧云朵#启动云朵移动动画(速度为3)
move_cloud(cloud1,3)
move_cloud(cloud2,3) #运行主循环
root.mainloop()
OK!