Python编写一个气泡屏保
时间: 2023-11-05 19:11:33 浏览: 47
好的,下面是一个简单的气泡屏保的 Python 代码:
```python
import tkinter as tk
import random
# 定义气泡类
class Bubble:
def __init__(self, canvas, x, y):
self.canvas = canvas
self.id = canvas.create_oval(x, y, x+30, y+30, fill='white')
self.vx = random.randint(-3, 3)
self.vy = random.randint(-3, 3)
self.canvas.move(self.id, self.vx, self.vy)
def update(self):
self.canvas.move(self.id, self.vx, self.vy)
pos = self.canvas.coords(self.id)
if pos[0] <= 0 or pos[2] >= 400:
self.vx = -self.vx
if pos[1] <= 0 or pos[3] >= 300:
self.vy = -self.vy
# 创建画布
root = tk.Tk()
root.title('Bubble Screensaver')
canvas = tk.Canvas(root, width=400, height=300)
canvas.pack()
# 创建若干个气泡
bubbles = []
for i in range(20):
x = random.randint(0, 370)
y = random.randint(0, 270)
bubbles.append(Bubble(canvas, x, y))
# 更新气泡的位置
while True:
for bubble in bubbles:
bubble.update()
root.update()
tk.sleep(0.01)
```
代码中使用了 tkinter 库,它提供了创建 GUI 界面的功能。首先创建一个画布,然后定义了一个气泡类,每个气泡都有一个随机的位置和速度。在主循环中,不断更新每个气泡的位置,并通过 `tk.sleep()` 控制屏幕的刷新率。运行代码后,你就可以看到屏幕上飘荡的气泡了。