Home > Software engineering >  Create grid then color it following given scenario in tkinter
Create grid then color it following given scenario in tkinter

Time:12-30

I want to create a grid and color some cells sequentially so that the user can see cells turning on.

For the moment I have:

from tkinter import *

center=Tk()
center.geometry('455x455')
center.title("9x9 grid")

cells = {}
for row in range(9):
     for column in range(9):
        cell = Frame(center, bg='white', highlightbackground="black",
                     highlightcolor="black", highlightthickness=1,
                     width=50, height=50,  padx=3,  pady=3)
        cell.grid(row=row, column=column)
        cells[(row, column)] = cell

def color_cell(cells, i, j, color="red"):
    cells[(i,j)].configure(background=color)

center.after(5000, color_cell(cells, 3, 4))

center.mainloop()

The problem is that I wait 5000ms before seeing everything. I want to see first the blank grid and then after 5000ms one of the cells turn red. End goal is to being able to illustrate a percolation algorithm (so the visualization has to be efficient). For the moment I chose Tkinter but that might be overkill, if you have a simpler alternative I'm all ears. Thanks.

CodePudding user response:

The problem is you call color_cell in center.after() instead of passing a reference to the function. You must do: center.after(5000, color_cell, cells, 3, 4):

center = Tk()
center.geometry('455x455')
center.title("9x9 grid")

cells = {}
for row in range(9):
     for column in range(9):
        cell = Frame(center, bg='white', highlightbackground="black",
                     highlightcolor="black", highlightthickness=1,
                     width=50, height=50, padx=3, pady=3)
        cell.grid(row=row, column=column)
        cells[(row, column)] = cell


def color_cell(cells, i, j, color="red"):
    cells[(i, j)].configure(background="red")


center.after(5000, color_cell, cells, 3, 4)

center.mainloop()
  • Related