A button_name:button_object dictionary (Tkinter)

vegaseat 2 Tallied Votes 1K Views Share

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()
CodingCabbage 0 Light Poster

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.