How do you update Tkinter parameters for buttons and labels created in a loop?

Viewed 118

Once an instance of a button has been created in a loop how is an individual button or label updated? Lets say I want to change the background on the 'North' button to 'blue'.

?????????.config(bg = 'blue')

What is the button name for the 'North' button in the code below?

import tkinter as tk

def onbutton_click(label):
    print('selected ', label)

lst = ['North','South','East','West']
win = tk.Tk()
win.title = 'Compass'
for col,Direction in enumerate(lst):
    buttonName = tk.Button(win, text=Direction, command=lambda e=Direction: onbutton_click(e))
    buttonName.grid(row=0, column=col)

win.mainloop()

This code is from another question answered by gms - thank you, that was a great answer, very clear! Tkinter create buttons from list each with its own function

2 Answers

You need some sort of reference to the button objects in order to access and modify them, after they are created in the loop.

One idea is to put them inside a dictionary whose key is the direction:

import tkinter as tk
    
def onbutton_click(label):
    print('selected ', label)

lst = ['North','South','East','West']
win = tk.Tk()
win.title = 'Compass'

button_dict = {}

for col,Direction in enumerate(lst):
    buttonName = tk.Button(win, text=Direction, command=lambda e=Direction: onbutton_click(e))
    buttonName.grid(row=0, column=col)
    button_dict[Direction] = buttonName

button_dict['North'].config(bg='blue')

win.mainloop()

Try this:

import tkinter as tk

def onbutton_click(label):
    print('selected ', label)
    if label == "North":
        # because "North" is the first item of `lst` we
        # know that we can use 0 as the idx
        buttons[0].config(text="new text here")

lst = ['North','South','East','West']
win = tk.Tk()
win.title = 'Compass'

# Create a list for all of the buttons
buttons = []

for col,Direction in enumerate(lst):
    buttonName = tk.Button(win, text=Direction, command=lambda e=Direction: onbutton_click(e))
    buttonName.grid(row=0, column=col)

    buttons.append(buttonName)

win.mainloop()

I created a dictionary of all of the buttons and directions like this: {"North": <Button>, "South": <Button>}. Then I used <dict>["North"] to get the button with the "North" label.

Related