magic_pet_plus/main.py

111 lines
3.4 KiB
Python
Raw Permalink Normal View History

import tkinter as tk #gui模块 主要共功能是创建窗口
from tkinter import messagebox
from PIL import Image, ImageTk
import os
import random
import pygame
# 初始化 pygame 播放器
pygame.mixer.init()
# 宠物信息(名字 + 描述 + 图像路径 + 声音路径)
pets = {
"fire": {
"name": "小火星",
"desc": "热情似火的小精灵,像火焰一样跳跃,能照亮黑暗的角落!",
"image": "./images/fire_pet.png",
"sound": "./sounds/fire.mp3"
},
"water": {
"name": "小水灵",
"desc": "爱在水中嬉戏的小可爱,总能带来清凉和欢乐的气息!",
"image": "./images/water_pet.png",
"sound": "./sounds/water.mp3"
},
"thunder": {
"name": "小电闪",
"desc": "全身带电的小家伙,跑得飞快,一不小心就“嗞啦”一下!",
"image": "./images/thunder_pet.png",
"sound": "./sounds/thunder.mp3"
},
"wind": {
"name": "小风灵",
"desc": "像风一样自由自在,轻盈地守护着大家,还会吹走烦恼哦!",
"image": "./images/wind_pet.png",
"sound": "./sounds/wind.mp3"
},
"earth": {
"name": "小土地",
"desc": "稳重又强壮的大地守护者,是伙伴们最坚实的后盾!",
"image": "./images/earth_pet.png",
"sound": "./sounds/earth.mp3"
},
"dark": {
"name": "小黑星",
"desc": "神秘的黑夜精灵,能在安静中保护大家不受惊吓!",
"image": "./images/dark_pet.png",
"sound": "./sounds/dark.mp3"
},
"light": {
"name": "小光星",
"desc": "闪闪发光的光明使者,总能把温暖和希望带给大家!",
"image": "./images/light_pet.png",
"sound": "./sounds/light.mp3"
},
}
# 创建主窗口
root = tk.Tk()
root.title("魔法宠物生成器")
root.geometry("400x500")
root.config(bg="lightyellow")
# 标题标签
title_label = tk.Label(root, text="🎉 你的魔法宠物诞生啦!", font=("Arial", 16, "bold"), bg="lightyellow")
title_label.pack(pady=10)
# 图像显示标签
image_label = tk.Label(root, bg="lightyellow")
image_label.pack(pady=10)
# 宠物介绍标签
info_label = tk.Label(root, text="", font=("Arial", 12), wraplength=300, justify="center", bg="lightyellow")
info_label.pack(pady=10)
# 保存照片引用(避免垃圾回收)
current_photo = None
# 生成宠物的函数
def generate_pet():
global current_photo
pet_type = random.choice(list(pets.keys()))
pet = pets[pet_type]
# 显示宠物描述
info_label.config(text=f"名字:{pet['name']}\n\n介绍:{pet['desc']}")
# 加载并显示图像(使用 Pillow
img_path = pet['image']
if os.path.exists(img_path):
img = Image.open(img_path).convert("RGB")
img = img.resize((200, 200))
photo = ImageTk.PhotoImage(img)
image_label.config(image=photo)
current_photo = photo # 避免图像被回收
else:
image_label.config(image='')
# 播放声音
sound_path = pet['sound']
if os.path.exists(sound_path):
pygame.mixer.music.load(sound_path)
pygame.mixer.music.play()
# 按钮
generate_button = tk.Button(root, text="🎲 生成魔法宠物", font=("Arial", 14), command=generate_pet, bg="skyblue")
generate_button.pack(pady=20)
# 启动主循环
root.mainloop()