Start New Discussion within our Software Development Community

Shows you how to create multiple Tkinter buttons in a loop, each with its own name, label and command response.

''' tk_button_object_dict102.py
create multiple buttons in a loop and
put them into a button_name:button_object dictionary
this dictionary can be added to Python's internal dictionary
tested with Python27 and Python33  by  vegaseat  21nov2013
'''

from functools import partial
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def click(val):
    sf = "Button {} clicked"
    root.title(sf.format(val))  # test

root = tk.Tk()
root.title("look at button two")
# or only set size of root
w = 250
h = 200
root.geometry("{}x{}".format(w, h))

# each button has its own name, label and command
button_name_list = [
'btn_one',
'btn_two',
'btn_three'
]

button_label_list = [
'one',
'two',
'three'
]

button_command_list = [
partial(click, 1),
partial(click, 2),
partial(click, 3)
]

# zip lists together to form a list of tuples
zip_list = zip(button_name_list, button_label_list, button_command_list)

btn_dict = {}
for name, label, cmd in zip_list:
    btn = tk.Button(root, text=label, width=15, command=cmd)
    btn.pack(pady=3)
    # create a button_name:button_object dictionary
    btn_dict[name] = btn 

print(btn_dict)  # test

# add the btn_dict to Python's local dictionary
# be careful that button names are unique
locals().update(btn_dict)

# for a test change the label of btn_two after 2000 milliseconds
root.update()
root.after(2000, btn_two.config(text='222 test'))

root.mainloop()

Would this work for adding data
(modules is a list)

button_name_list = [
]
for count2 in range(0,len(modules)+1, 1):
    button_name_list.append(modules[count2] + "Button")
    count2 = count2+1
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.