Selecting an element on a tkinter python frame

Question:

I am writing a simple GUI with standard Tkinter (python) elements. On the main screen of the application, there are several identical frame containers with the same elements such as button, entry, label.

To adhere to the golden rule of DRY, I create elements in frames (and the frames themselves) in a loop like this:

for frames in range(3):
    tab = Frame(mainWindow)

    for elements in range(1, 5):

        alarmH = Entry(tab, width=2)
        alarmH.grid(column=0, row=elements)

        sounds = Combobox(tab, values=soundList)
        sounds.set("Select")
        sounds.grid(column=4, row=elements)

и т.д.

So now the question is how to refer to a separate element of one of the frames (for example, to change the text or background of an element). Is it even possible?

I suspect that you need to move everything into separate variables manually, but still …

Answer:

You can save links to items in lists or dictionaries.

For example like this:

frames = {}

for i in range(3):

    frames[i] = {}
    tab = Frame(mainWindow)
    frames[i]['tab'] = tab
    frames[i]['elements'] = {}
    for j in range(1, 5):
        frames[i]['elements'][j] = {}
        alarmH = Entry(tab, width=2)
        alarmH.grid(column=0, row=elements)
        frames[i]['elements'][j]['entry'] = alarmH
        sounds = Combobox(tab, values=soundList)
        sounds.set("Select")
        sounds.grid(column=4, row=elements)
        frames[i]['elements'][j]['combobox'] = sounds

And then you can refer to a specific element through the dictionary:

To a specific taboo:

print(frames[0]['tab'])

Or to a specific element:

frames[1]['elements'][0]['combobox'].set("Select")
Scroll to Top