自制PY桌宠
2025-03-16 20:04:21
发布于:北京
图片在这里(记得缩小):
源代码:
import tkinter as tk
import random
# 创建主窗口
root = tk.Tk()
root.overrideredirect(True) # 去除窗口边框
root.attributes("-topmost", True) # 窗口始终置顶
root.attributes("-alpha", 0.8) # 设置窗口透明度
# 加载小猫图片
try:
cat_image = tk.PhotoImage(file="cat.png")
except tk.TclError:
print("未找到图片文件 'cat.png',请确保图片文件存在。")
root.destroy()
raise
# 创建标签显示小猫图片
cat_label = tk.Label(root,image=cat_image)
cat_label.pack()
# 获取屏幕尺寸
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# 初始位置
x = random.randint(0, screen_width - cat_image.width())
y = random.randint(0, screen_height - cat_image.height())
root.geometry(f"+{x}+{y}")
# 移动小猫的函数
def move_cat():
global x, y
# 随机生成移动方向
dx = random.randint(-5, 5)
dy = random.randint(-5, 5)
# 计算新位置
new_x = x + dx
new_y = y + dy
# 确保小猫不会移出屏幕
if 0 <= new_x <= screen_width - cat_image.width():
x = new_x
if 0 <= new_y <= screen_height - cat_image.height():
y = new_y
# 更新窗口位置
root.geometry(f"+{x}+{y}")
# 每隔 100 毫秒调用一次 move_cat 函数
root.after(100, move_cat)
# 绑定鼠标事件,使窗口可以拖动
def on_drag_start(event):
global drag_x, drag_y
drag_x = event.x
drag_y = event.y
def on_drag_motion(event):
global x, y
dx = event.x - drag_x
dy = event.y - drag_y
x += dx
y += dy
root.geometry(f"+{x}+{y}")
cat_label.bind("<ButtonPress-1>", on_drag_start)
cat_label.bind("<B1-Motion>", on_drag_motion)
# 开始移动小猫
move_cat()
# 运行主循环
root.mainloop()
全部评论 1
为什么用不了
2025-03-20 来自 北京
0
有帮助,赞一个