You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter按钮添加图片后GUI空白无响应,求图片适配按钮方案

解决Tkinter国际象棋棋盘图片适配问题

问题核心原因

取消注释添加棋子图片的代码后GUI全白且无法点击,主要有两个问题:

  • 未缩放的棋子图片尺寸过大,撑破了按钮的网格布局,导致界面错乱
  • 直接在按钮配置中创建ImageTk.PhotoImage对象,没有保留引用,会被Python垃圾回收机制清理,进而引发显示异常

解决方案

1. 实现图片比例缩放

用PIL的Image模块读取图片,按棋盘格子的尺寸等比例缩放,确保图片适配按钮大小。

2. 保留图片对象引用

将所有棋子的PhotoImage对象存入列表,避免被垃圾回收。

修改后的完整代码

from tkinter import Tk, Label, Button
from pathlib import Path
from PIL import ImageTk, Image

# 配置资源路径
root = str(Path.cwd()) + r"\assets"

window = Tk()
window.title("Jeu d'echec")
window.geometry("560x700")
window.resizable(0,0)

window.rowconfigure(0, weight = 1)
window.rowconfigure(9, weight = 1)

for i in range(8):
    window.rowconfigure(i+1, weight=2)
    window.columnconfigure(i, weight=2)

squares = []
# 存储图片引用,防止被垃圾回收
piece_images = []

for i in range(64) :
    btn = Button(window, bg = ["white", "black"][(i+i//8)%2], relief="flat", borderwidth=0)
    btn.grid(column = i%8, row = 1 + (i//8), sticky="nsew")
    squares.append(btn)

# 按目标尺寸等比例缩放图片
def resize_image(image_path, target_size):
    img = Image.open(image_path)
    # 保持图片比例,避免拉伸变形
    img.thumbnail(target_size)
    return ImageTk.PhotoImage(img)

# 窗口宽度560px,8列格子,每格目标尺寸设为70x70
target_size = (70, 70)
# 添加白兵图片
pawn_img = resize_image(root + "\WhitePawn.png", target_size)
piece_images.append(pawn_img)
# 让图片居中显示,不覆盖按钮背景
squares[4].config(image=pawn_img, compound="center")

# 分数标签
black_score_label = Label(window, text="Black = 0")
white_score_label = Label(window, text="White = 0")

black_score_label.grid(row = 0, columnspan=8)
white_score_label.grid(row = 9, columnspan=8)

window.mainloop()

关键说明

  • thumbnail()方法会保持图片的宽高比,避免棋子出现拉伸变形的情况
  • piece_images列表专门存储图片对象,确保Python不会回收这些资源
  • compound="center"参数让图片居中显示在按钮上,同时保留按钮原本的背景色

内容的提问来源于stack exchange,提问作者Ayogo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:30:07