How would I use classes stored in a dictionary as callback functions for a button?

34 Views Asked by At

I have a dictionary of classes that correspond with a section name, with each class representing each section. When the GUI is being created I don't know how many sections will be in the dictionary. My solution was to loop over the sections and for each section that exists, create a button and associate the corresponding class as a callback.

import Tkinter as tk

class SectionClass:
     def __init__(self):
          print("Created SectionClass")

class AnotherClass:
     def __init__(self):
          print("Created AnotherClass")


SectionDict = dict()

SectionDict["SectionClass"] = SectionClass
SectionDict["AnotherClass"] = AnotherClass

root = tk.Tk()

frame = tk.Frame(root, height=160, width=100,).grid(row=0, column=0)

row_iterator = 0
for section in SectionDict:
     tk.Label(frame, text=section).grid(row = row_iterator, column=0)
     tk.Button(frame, text="Create Section", command=lambda:   SectionDict[section]()).grid(row = row_iterator, column = 1)
     row_iterator += 1

root.mainloop()

Both buttons will only create the SectionClass. What gives?

0

There are 0 best solutions below