使用Tkinter与Pillow开发21点GUI的图片显示及布局问题
21点GUI游戏开发问题解决
问题1:卡牌图片无法正常显示
你遇到的图片只显示空白占位的问题,核心原因是路径加载不稳定以及Label控件未匹配父容器背景,修复方案如下:
- 引入os模块拼接绝对路径,避免运行时工作目录变化导致找不到图片
- 给承载图片的Label指定父容器,同时设置背景色和游戏桌背景一致,避免透明边框遮挡
对应修改后的图片加载代码:
import os # 先获取当前代码文件的所在目录 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) img_path = os.path.join(BASE_DIR, "PNG", "2C.png") # 加载并调整图片尺寸 image1 = Image.open(img_path) # 高版本Pillow用Image.Resampling.LANCZOS,低版本Pillow替换为Image.ANTIALIAS resize_img1 = image1.resize((50, 100), Image.Resampling.LANCZOS) real_img = ImageTk.PhotoImage(resize_img1) # 给Label指定父容器,设置背景色和窗口一致 panel1 = tk.Label(window, image=real_img, bg="#0C8702") panel1.image = real_img
问题2:卡牌定位布局方案
推荐你用Frame+Grid混合布局,兼顾你熟悉Frame的使用习惯,同时方便区域划分,布局逻辑如下:
- 整个窗口垂直划分3个独立Frame区域:
- 顶部庄家卡牌区:固定在窗口上半部分,对应截图里上方红框
- 中部玩家卡牌区:固定在窗口下半部分,对应截图里下方红框
- 底部按钮区:保留已实现的按钮栏逻辑
- 每个卡牌区内部新增卡牌时,用
pack(side="left", padx=3)即可实现横向并列摆放,自动适配卡牌数量
完整修改后的运行代码如下:
import tkinter as tk from tkinter import ttk from PIL import ImageTk, Image import os def hit(): print("hit was pressed") def stand(): print("stand was pressed") def new_hand(): print("new hand was pressed") # 创建窗口 window = tk.Tk() window.title("Black Jack") window.geometry("800x600") window.configure(bg="#0C8702") # 1. 顶部庄家卡牌区 dealer_frame = tk.Frame(window, bg="#0C8702", height=200) dealer_frame.pack(side="top", fill="x", pady=30) # 测试加载庄家卡牌 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) img_path = os.path.join(BASE_DIR, "PNG", "2C.png") image1 = Image.open(img_path) resize_img1 = image1.resize((50, 100), Image.Resampling.LANCZOS) real_img = ImageTk.PhotoImage(resize_img1) dealer_card1 = tk.Label(dealer_frame, image=real_img, bg="#0C8702") dealer_card1.image = real_img dealer_card1.pack(side="left", padx=5) # 2. 中部玩家卡牌区 player_frame = tk.Frame(window, bg="#0C8702", height=200) player_frame.pack(side="top", fill="x", pady=50) # 测试加载玩家卡牌 player_card1 = tk.Label(player_frame, image=real_img, bg="#0C8702") player_card1.pack(side="left", padx=5) # 3. 底部按钮区 buttons = ttk.Frame(window, padding=(20,10,20,0)) buttons.pack(side="bottom", fill="both") hit_button = ttk.Button(buttons, text="Hit", command=hit) hit_button.pack(side="left",fill="x", padx=10) stand_button = ttk.Button(buttons, text="Stand", command=stand) stand_button.pack(side="left",fill="x", padx=10) deal_new_hand_button = ttk.Button(buttons, text="New Hand", command=new_hand) deal_new_hand_button.pack(side="left", fill="x", padx=10) quit_button = ttk.Button(buttons, text="Quit", command=window.destroy) quit_button.pack(side="left", fill="x", padx=10) window.mainloop()

内容的提问来源于stack exchange,提问作者David Em-Yinn
相关产品推荐
相关产品推荐

