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

tkmacosx按钮设置图片后移位至左上角的问题解决求助

tkmacosx 按钮动态设置图片后移位问题解决

问题描述

使用tkmacosx 1.0.5版本创建两个600×500的按钮:

  • 一个按钮默认显示图片,显示正常
  • 点击另一个按钮加载同一张图片时,图片会偏移到按钮左上角,仅部分可见
  • 切换place()、pack()布局,问题依然存在
  • 原生tkinter的Button可正常显示图片,但macOS环境下tkinter存在其他功能缺陷,因此需解决tkmacosx的该问题

问题代码

import tkinter as tk
from tkmacosx import Button

root = tk.Tk()

my_img = tk.PhotoImage(file='img.png')

def pressed(but):
    but.config(image=my_img)

b_1 = Button(root, bg='white', width=600, height=500)
b_2 = Button(root, bg='white', width=600, height=500)

b_1.config(command=lambda b=b_1: pressed(b))
b_2.config(command=lambda b=b_2: pressed(b))

b_1.config(image=my_img)

b_1.grid(column=1, row=1)
b_2.grid(column=2, row=1)

root.mainloop()

问题截图

  • 点击前效果:点击按钮前的显示效果
  • 点击后效果:点击按钮后的显示效果

解决方案

方案1:显式指定图片居中布局

在动态设置图片时,添加compound='center'参数,强制图片在按钮内居中显示:

def pressed(but):
    but.config(image=my_img, compound='center')

方案2:重置按钮尺寸触发重绘

设置图片前先重置按钮的宽高,触发组件重算布局:

def pressed(but):
    but.config(width=600, height=500)
    but.config(image=my_img)

方案3:升级tkmacosx版本

该布局bug在tkmacosx 1.1.0及后续版本中已修复,执行以下命令升级:

pip install --upgrade tkmacosx

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:47:27