动态爱心python代码
时间: 2023-11-26 21:48:44 浏览: 338
以下是一个简单的动态爱心 Python 代码,它使用了 Tkinter 库中的 Canvas 控件来绘制图形界面,实现了一个动态的爱心效果:
```python
import tkinter as tk
import math
class Heart:
def __init__(self, canvas, x, y, size):
self.canvas = canvas
self.x = x
self.y = y
self.size = size
self.draw()
def draw(self):
x = self.x
y = self.y
size = self.size
self.shapes = []
for i in range(200):
t = i / math.pi
x = 16 * math.sin(t) ** 3
y = 13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t)
x = x * size + self.x
y = y * size + self.y
self.shapes.append(self.canvas.create_line(x, y, x + 1, y + 1, fill='red'))
def move(self):
for i in range(len(self.shapes)):
t = i / math.pi
x = 16 * math.sin(t) ** 3
y = 13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t)
x = x * self.size + self.x
y = y * self.size + self.y
self.canvas.coords(self.shapes[i], x, y, x + 1, y + 1)
class App:
def __init__(self, master):
self.master = master
self.canvas = tk.Canvas(master, width=400, height=400)
self.canvas.pack()
self.heart = Heart(self.canvas, 200, 200, 10)
self.animate()
def animate(self):
self.heart.move()
self.master.after(10, self.animate)
root = tk.Tk()
app = App(root)
root.mainloop()
```
阅读全文