D-slr8
D-slr8

Reputation: 109

tkinter - linking buttons in a for loop to a dictionary of functions {name : function}

I am trying to create a rather large list of buttons in a for loop that is also linked to their corresponding function to be called in a dictionary. There are a few similar posts here and here that discuss using lambda assigning the name=name, but I cant seem to figure out how to incorporate that into this specific instance where each one calls a different function in the dictionary, rather than altering a single parameter of single function. Here is an example.

import tkinter as tkinter    
root = tkinter.Tk()

def funct1():
    print("Printed Func1")
def funct2():
    print("Printed Func2")

buttons_dict = {"button1": "Func1", "button2": "Func2"}

row = 0
for name in buttons_dict:
    buttons = tkinter.Button(root, text=name) # command=lambda name=name: root(name))
    buttons.grid(row=row)
    buttons.config()
    row += 1

root.mainloop()

What would be the correct method for assigning the name to the function when gathering the information from a dictionary like this?

Upvotes: 1

Views: 183

Answers (1)

brandonwang
brandonwang

Reputation: 1653

You can reference the function in the dictionary like this:

import tkinter as tkinter    
root = tkinter.Tk()

def funct1():
    print("Printed Func1")
def funct2():
    print("Printed Func2")

buttons_dict = {"button1": funct1, "button2": funct2}

row = 0
for name in buttons_dict:
    buttons = tkinter.Button(root, text=name, command=buttons_dict[name])
    buttons.grid(row=row)
    buttons.config()
    row += 1

root.mainloop()

Upvotes: 4

Related Questions