Home > Software design >  Run functions from list
Run functions from list

Time:12-07

trying to get the selected values from a list of checkbutton without having to create 10 or more checbutton and var.

i got this to test the idea

from tkinter import Tk, StringVar, Checkbutton, Button, BooleanVar

root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d 0 0" % (w, h))



def def1():
    print("1")

def def2():
    print("2")

def def3():
    print("3")

def def4():
    print("4")

def def5():
    print("5")

def def6():
    print("6")

def letssee():
   print(addlist)



nomtestes = ["def1", "def2", "def3", "def4", "def5", "def6"]

clltes = 0
rwwtes = 0
addlist=[]
username_cbs = dict()
for name in nomtestes:
    if clltes == 5:
        rwwtes  = 1
        clltes = 0
    username_cbs[name] = Checkbutton(root, text=name, onvalue=True, offvalue=False)
    username_cbs[name].var = BooleanVar()
    username_cbs[name]['variable'] = username_cbs[name].var
    username_cbs[name]['command'] = lambda w=username_cbs[name]: upon_select(w)
    username_cbs[name].grid(row=rwwtes, column=clltes, pady=2)
    clltes  = 1

Button(root, text="OK",command=letssee).grid(column=0, row=5, padx=1, pady=15)


def upon_select(widget):
    if widget.var.get() == True:
        addlist.append(widget['text'])
    else:
        addlist.remove(widget['text'])

root.mainloop()

In this example im trying to print all the checkbuttons i selected, but, to run the funcions added to the addlist

Any ideia how to do this?

thanks

CodePudding user response:

You can create a dictionary, mapping string values to respective functions and then add or remove them to a list.

nomtestes = {"def1": def1, "def2": def2, "def3": def3, "def4": def4, "def5": def5, "def6": def6}
addlist = list()
from_input = ["def1", "def4"]
for i in from_input:
    addlist.append(nomtestes[i])

for def_function in addlist:
    def_function()

Out: 1
     4
  • Related