首页 > 解决方案 > 无法使用按钮命令更新 tkinter 网格

问题描述

当我单击按钮以转到新颜色时,我正在尝试更新此网格中的所有颜色框,但该按钮似乎不起作用。每当按下按钮时,它应该调用 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 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()

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()

标签: pythontkinter

解决方案


推荐阅读