0

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?

prototypik
  • 2,726
  • 1
  • 18
  • 21
  • Thanks for the link, it answered my question. – prototypik Jun 10 '15 at 16:50
  • Feel free to vote on that answer if you found it useful. – TigerhawkT3 Jun 10 '15 at 17:10
  • As an aside: there is no use in creating a `lambda` wrapper if you aren't actually changing the parameters. `lambda: SectionDict[section]()` is logically equivalent to `SectionDict[section]`, except that the latter will not cause the late binding issue. However, you won't actually be able to use the classes as callbacks like that, because Tkinter will pass parameters that you aren't accounting for (in `__init__`). – Karl Knechtel Aug 16 '22 at 01:52

0 Answers0