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

使用按钮命令无法更新tkinter grid网格颜色块问题如何解决

问题原因

  • 按钮绑定错误:command参数需要传入函数对象本身,你写的displayGrid()带了括号,会在程序初始化时直接执行该函数,将返回的None赋值给点击触发逻辑,导致点击按钮时无执行目标。
  • 未清空旧网格:就算修复绑定逻辑,重复调用displayGrid()会在容器内堆叠新生成的色块,不会替换旧内容。

修复方案

修改后的完整代码如下,已标注改动点:

import tkinter as tk
from tkinter import *
import random

window = tk.Tk()

containerFrame = LabelFrame(window, text = "Color Picker Grid", highlightthickness = 5)

def displayGrid(): 
    # 新增:清空容器内所有旧控件,避免色块堆叠
    for widget in containerFrame.winfo_children():
        widget.destroy()

    for x in range(5):
        containerFrame.columnconfigure(x, weight=1, minsize=75)
        containerFrame.rowconfigure   (x, weight=1, minsize=75)

        for y in range(5):
            gridFrame = tk.Frame(
                master = containerFrame,
                relief = tk.RAISED,
                borderwidth = 3
            )

            gridFrame.grid(row = x, column = y, padx = 5, pady = 5)  # Sets position of the color square
            gridColor = "#" + ("%06x" % random.randint(0, 0xFFFFFF)) # Creates the randomized color
            gridLabel = tk.Label(                                    # Creates the square itself with the color
                master = gridFrame, 
                text = gridColor,
                font = ('arial bold', '12'),
                fg = "white",
                anchor = "sw",
                height = 10,
                width = 20,
                bg = gridColor
            )

            gridLabel.pack(padx = 5, pady = 5)
            
    containerFrame.pack(fill = "both", expand = "yes")

displayGrid()

# 修改:去掉displayGrid后的括号,传入函数对象本身
refreshButton = Button(window, text = "Refresh", command = displayGrid)
refreshButton.pack(padx = 5, pady = 5)

# To-do, put a black background behind the white text, figure out how to refresh the page for colors and all that

window.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 00:45:02