代码示例
from tkinter import Tk, Canvas, Label
from PIL import Image, ImageTk
import random
# 初始化分数和游戏时间
score = 0
game_time = 30 # 游戏持续时间
# 点击地鼠时增加分数
def hit_mole(event):
global score
canvas.delete("mole")
score += 1
score_label.config(text=f"得分: {score}")
# 随机显示地鼠
def show_mole():
if game_time > 0:
x = random.randint(50, 450)
y = random.randint(50, 350)
canvas.delete("mole")
canvas.create_image(x, y, image=mole_img, tags="mole")
canvas.tag_bind("mole", "<Button-1>", hit_mole) # 点击事件绑定
root.after(1000, show_mole) # 每秒刷新一次
# 更新倒计时
def update_time():
global game_time
if game_time > 0:
game_time -= 1
time_label.config(text=f"剩余时间: {game_time}秒")
root.after(1000, update_time)
else:
canvas.delete("mole")
canvas.create_text(250, 200, text="游戏结束!", font=("Arial", 24), fill="red")
# 设置窗口
root = Tk()
root.title("打地鼠游戏")
# 设置画布并设置背景色
canvas = Canvas(root, width=500, height=400, bg="#DACBB7") # 设置背景色为 RGB (218, 203, 183)
canvas.pack()
# 显示分数
score_label = Label(root, text="得分: 0", font=("Arial", 14))
score_label.pack()
# 显示时间
time_label = Label(root, text=f"剩余时间: {game_time}秒", font=("Arial", 14))
time_label.pack()
# 使用 Pillow 加载地鼠图片
image = Image.open("dishu.png") # 这里是地鼠图片的路径
mole_img = ImageTk.PhotoImage(image)
# 启动游戏
root.after(1000, show_mole)
root.after(1000, update_time)
root.mainloop()
效果展示
有兴趣的小伙伴可以关注我的公众号【知识星球站】一起讨论学习!!