python画跳动的爱心代码
时间: 2023-08-08 22:10:58 浏览: 176
以下是一个用Python画跳动的爱心的代码示例:
```python
from tkinter import *
from math import sin, cos
from random import random, log
CANVAS_WIDTH = 800
CANVAS_HEIGHT = 600
CANVAS_CENTER_X = CANVAS_WIDTH // 2
CANVAS_CENTER_Y = CANVAS_HEIGHT // 2
class Heart:
def __init__(self):
self.color = "#ff8181" # 心的颜色,这里使用了粉色
self.shrink_ratio = 1.5 # 放大比例
def render(self, canvas, frame):
t = frame / 100 # 参数t,控制心的形状
x = 16 * (sin(t) ** 3)
y = -(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))
x *= self.shrink_ratio
y *= self.shrink_ratio
x, y = self.scatter_inside(x, y) # 随机内部扩散
canvas.create_oval(CANVAS_CENTER_X + x - 2, CANVAS_CENTER_Y + y - 2,
CANVAS_CENTER_X + x + 2, CANVAS_CENTER_Y + y + 2,
fill=self.color) # 在画布上绘制一个小圆点
def scatter_inside(self, x, y, beta=0.15):
ratio_x = - beta * log(random())
ratio_y = - beta * log(random())
dx = ratio_x * (x - CANVAS_CENTER_X)
dy = ratio_y * (y - CANVAS_CENTER_Y)
return x - dx, y - dy
def draw(main, render_canvas, render_heart, render_frame=0):
render_canvas.delete('all')
render_heart.render(render_canvas, render_frame)
main.after(160, draw, main, render_canvas, render_heart, render_frame + 1)
if __name__ == '__main__':
root = Tk()
canvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)
canvas.pack()
heart = Heart()
draw(root, canvas, heart)
root.mainloop()
```
这段代码使用了Tkinter库来创建一个窗口,并在窗口中绘制一个跳动的爱心。通过调整参数t的值,可以控制爱心的形状。同时,还使用了随机内部扩散的方法,使爱心在画布上有轻微的抖动效果。
#### 引用[.reference_title]
- *1* *2* *3* [Python制作爱心跳动代码,这就是程序员的烂漫吗](https://blog.csdn.net/aliYz/article/details/127796534)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文