sairate c4d32e8092 feat(第7讲 字母卡牌): 实现记忆游戏并添加开始界面
- 新增 jiyi.py 文件,实现字母翻牌记忆游戏功能
- 添加 youxijiemian.py 文件,创建游戏开始界面
- 使用 turtle 和 tkinter 模块分别实现游戏和界面
- 支持选择不同难度的游戏模式
2025-06-28 14:27:31 +08:00

114 lines
3.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'''
【一、导入库】
'''
# 预置内容,请勿改动
import io
import base64
import cv2
# 请在下方编写代码
import tkinter as tk
from PIL import Image, ImageTk
from tkinter import filedialog
'''
【二、初始化】变量初始化、窗口初始化、API配置信息
'''
# 预置内容,请勿改动
cap = None
imgtk = None
update_id = None
# 请在下方编写代码
# 初始化Tkinter
root = tk.Tk()
root.geometry('700x700')
root.title('颜值测评')
root.resizable(0, 0)
'''
【三、函数】
'''
# 预置内容,请勿改动 图像 --> 字节数据 --> Base64 编码格式
def img_to_bytes(photoimg):
# 将 PhotoImage 转换为 PIL 图像
pil_img = ImageTk.getimage(photoimg)
# 如果图像具有 Alpha 信道(透明度),则转换为 RGB
if pil_img.mode == 'RGBA':
pil_img = pil_img.convert('RGB')
# 保存到字节缓冲区
buffer = io.BytesIO()
pil_img.save(buffer, format='JPEG')
img_data = buffer.getvalue()
return base64.b64encode(img_data).decode('utf-8')
# 预置内容,请勿改动 打开摄像头
def open_camera():
global cap, update_id
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("无法打开摄像头")
return
def update_frame():
global cap, update_id
ret, frame = cap.read()
if frame is None:
return
frame = cv2.resize(frame, (250, 250))
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = Image.fromarray(frame)
imgtk = ImageTk.PhotoImage(img)
lab_photo.imgtk = imgtk
lab_photo.config(image=imgtk)
update_id = lab_photo.after(10, update_frame)
update_frame()
# 预置内容,请勿改动 关闭摄像头
def close_camera():
global cap, update_id
if cap is not None:
cap.release()
cap = None
if update_id is not None:
lab_photo.after_cancel(update_id)
update_id = None
lab_photo.imgtk = imgtk
lab_photo.config(image=imgtk)
# 请在下方编写代码
# 加载本地图片
def load():
file_path = filedialog.askopenfilename() # 打开一个文件选择对话框
if file_path:
close_camera()
img = Image.open(file_path)
img = img.resize((250, 250))
imgtk = ImageTk.PhotoImage(img)
lab_photo.imgtk = imgtk
lab_photo.config(image=imgtk)
# 颜值检测开始
def ok():
pass
'''
【四、组件配置】
'''
# 设置背景图
bg_image = tk.PhotoImage(file = '测颜值.png')
bg_label = tk.Label(root, image = bg_image)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)
# 设置缩略图
pic0 = Image.open('缩略图.png')
pic0 = pic0.resize((250, 250))
pic0_image = ImageTk.PhotoImage(pic0)
lab_photo = tk.Label(root, image=pic0_image)
lab_photo.place(x=223, y=223)
# 本地上传按钮
btn_load = tk.Button(root, text="本地上传", command=load, width=15, height=2, font=("楷体", 12))
btn_load.place(x=115, y=625)
# 拍照上传按钮
btn_cam = tk.Button(root, text="拍照上传", command=open_camera, width=15, height=2, font=("楷体", 12))
btn_cam.place(x=300, y=625)
# 开始测评按钮
btn_enter = tk.Button(root, text="点击开测!", command=ok, width=15, height=2, font=("楷体", 12))
btn_enter.place(x=485, y=625)
'''
【五、启动事件循环】
'''
root.mainloop()