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

Tkinter按钮重叠问题求助:代码运行后按钮重叠原因排查

问题原因及解决方法

核心问题

你所有组件都复用了main_action变量,把最初的主窗口对象覆盖成了Label、Button,导致后续按钮的父容器不是主窗口,而是前一个按钮组件,最终所有按钮嵌套在一起出现重叠。另外主窗口只配置了0、1、2列,但代码里用到了3、4列,这些未配置的列也会干扰布局效果。

修正后的代码

import tkinter as tk

# 主窗口单独命名,避免被后续组件覆盖
root = tk.Tk()
root.geometry("600x600")
root.title("Keymanager")
root.resizable(0, 0)

# 配置所有用到的列的权重,保证布局分配合理
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=3)
root.columnconfigure(2, weight=4)
root.columnconfigure(3, weight=3)
root.columnconfigure(4, weight=3)

# 每个组件使用独立变量名,父容器明确指定为主窗口root
title_label = tk.Label(root, text="Escoja que accion quiere realizar")
title_label.grid(column=1, row=0, sticky=tk.E, padx=5, pady=5)

view_btn = tk.Button(root, text="Ver")
view_btn.grid(column=1, row=2, sticky=tk.E, padx=5, pady=5)

add_btn = tk.Button(root, text="Añadir")
add_btn.grid(column=2, row=2, sticky=tk.E, padx=5, pady=5)

delete_btn = tk.Button(root, text="Eliminar")
delete_btn.grid(column=3, row=2, sticky=tk.E, padx=5, pady=5)

exit_btn = tk.Button(root, text="Salir")
exit_btn.grid(column=4, row=2, sticky=tk.E, padx=5, pady=5)

root.mainloop()

关键改动点

  • 主窗口使用独立变量名root,不再被后续组件覆盖
  • 每个组件单独命名,父容器明确指定为主窗口root
  • 为用到的3、4列添加权重配置,保证各列布局空间分配合理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:22:34