Search code examples
pythontkintercustomtkinter

Assigning a specific name to a Tkinter frame in a for loop using Python


I'm new to Python and GUI developmment.

I'm trying to display in a window a week planning. I have prepared a list of days, and I want to loop through to create a frame for each day :

Frames for the week

This part is ok, my issue is to assign the name of the frame like so : Monday_frame ; Tuesday_frame...

I could do it directly in the code for 7 frames, but I would like to understand the possibility to do it inside a for loop.

Here is my trial, but I don't understand how to add my "day" value to replace the "day" in "day_frame". (I'm using CustomTkinter instead of Tkinter for the interface, that's why there is the "CTk" instead "Tk" in code below.)

week = ['Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi','Dimanche']

for day in week:
    day_frame = CTkFrame(master=week_frame, bg_color=window_color,border_color='white',border_width=2,fg_color=window_color)
    day_frame.pack(side=LEFT, fill=Y, expand=YES) 

EDIT :

No dynamical naming for the frames, using a dictionnary as proposed, days as keys and frames as values. See below code and example of use : (small differences in pictures due to other changes. See white foreground of 2nd day as example of dictionnary use.)

    week = ['Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi','Dimanche']

frames = {}
for day in week:
    day_frame = CTkFrame(master=week_frame, bg_color=window_color,border_color='white',border_width=2,fg_color=window_color)
    day_frame.pack(side=LEFT, fill=Y, expand=YES)
    frames[day] = day_frame

frames['Mardi'].configure(fg_color='white')

Frames for the week after edit


Solution

  • Don't try to dynamically create variable names. Use a dictionary:

    frames = {}
    for day in week:
        day_frame = CTkFrame(master=week_frame, bg_color=window_color,border_color='white',border_width=2,fg_color=window_color)
        day_frame.pack(side=LEFT, fill=Y, expand=YES) 
        frames[day] = day_frame
    

    With that, you can later use something like frames["Sunday"] to access the frame.