桌宠源代码 python
时间: 2023-05-09 15:03:46 浏览: 165
桌宠源代码Python是一种可以在电脑桌面上放置小型宠物的程序,使用Python语言编写。该程序可以自主运动,还有各种表情和动作,例如眨眼、摇头、扭屁股等。下面是一个简单的桌宠源代码Python:
``` python
import tkinter as tk
import random
class DesktopPet:
def __init__(self, master):
self.master = master
self.master.geometry('100x100')
self.master.overrideredirect(True)
self.master.attributes('-topmost', True)
self.master.configure(background='white')
self.width = self.master.winfo_screenwidth()
self.height = self.master.winfo_screenheight()
self.master.bind('<Button-1>', self.on_surface_clicked)
self.master.bind('<B1-Motion>', self.on_surface_dragged)
self.master.bind('<KeyPress>', self.on_key_pressed)
self.pet_img = tk.PhotoImage(file='pet.gif')
self.pet_label = tk.Label(self.master, image=self.pet_img)
self.pet_label.pack()
self.pet_label.bind('<Button-1>', self.on_surface_clicked)
self.pet_label.bind('<B1-Motion>', self.on_surface_dragged)
self.pet_label.bind('<Button-2>', self.on_eye_clicked)
self.x = random.randint(0, self.width - 100)
self.y = random.randint(0, self.height - 100)
self.dx = random.random() * 2 - 1
self.dy = random.random() * 2 - 1
def move(self):
self.x += self.dx
self.y += self.dy
if self.x < 0 or self.x > self.width - 100:
self.dx = -self.dx
if self.y < 0 or self.y > self.height - 100:
self.dy = -self.dy
self.master.geometry('+%d+%d' % (self.x, self.y))
self.master.after(100, self.move)
def on_surface_clicked(self, event):
self.dx = 0
self.dy = 0
def on_surface_dragged(self, event):
self.x = event.x
self.y = event.y
def on_key_pressed(self, event):
if event.char == 'q':
self.master.quit()
def on_eye_clicked(self, event):
pass
if __name__ == '__main__':
root = tk.Tk()
pet = DesktopPet(root)
pet.move()
root.mainloop()
```
以上是一个简单的桌宠源代码Python,宠物会随机移动,当用户单击或拖动宠物时,它将停止移动,用户还可以按下“q”键退出程序。如果用户单击眼睛,则可以实现其他互动效果。程序可以根据实际需要进行修改,增加更多功能并进行优化以提高可玩性。
阅读全文