Home > Software engineering >  How to use Tkinter config on a grid of frames?
How to use Tkinter config on a grid of frames?

Time:03-25

It's my first question so I'll try to word this the best I can. I have a 5x6 grid of frames in my python program. I am attempting to utilize the config function within Tkinter to alter the properties of select frames within the grid.

Here's the code where I create the grid:

for i in range(5):
  for j in range(6):
    frame = Frame(holder,bg="white",width=32,height=32, borderwidth=1, relief="raised")
    frame.grid(row = j, column = i, padx = 3, pady = 3)

And here's the line attempting to alter the colour: frame.config(bg="red")

I have tried things like frame[x][y], looping, etc and after a lot of searching and reading up on the config function I couldn't find a solution. All it does right now is change the bottom right frame of the grid to red, when I want to change only specific frames.

Any help is GREATLY appreciated!

CodePudding user response:

You have to store the Frames you created somewhere, in a 2D List for example. Right now you just create the frames but override the variable frame with a new frame every time. So you can only access the last Frame you created.

A solution would be:

# create empty 2D List with list comprehension
frame_list = [[None for i in range(6)] for j in range(5)]

# create the Frames
for i in range(5):
    for j in range(6):
        frame = Frame(holder,bg="white",width=32,height=32, borderwidth=1, relief="raised")
        frame.grid(row = j, column = i, padx = 3, pady = 3)

        frame_list[i][j] = frame  # add frame to 2D list

# configure a specific Frame from the list
frame_list[0][0].config(bg="red")
  • Related