Home > Net >  Is there a way to set the command in a Tkinter Button at run time without Eval()
Is there a way to set the command in a Tkinter Button at run time without Eval()

Time:06-10

As the title says is there another way to get this python script to set the command for a button at run time without using eval(), I'm aware it's a really - really - stupid way of doing it but I can't for the life of me work out how else to do it.

The Command needs to be set when creating each button object and as such I can't preset it.

I've tried regular input and fstring input but can't think of anything else, any help would be appreciated

root = Tk()
root.title("SOP")
root.geometry("1920x1080")

class CreateGui(object):
    def __init__(self, master):
        self.master = master
        myFrame = Frame(master)
        myFrame.pack()

    def CreateButton(self, lines, target):
        self.myButton = Button(self.master, text=lines, command=eval(target))
        print(target)
        self.myButton.pack(pady=20)

    def clicker(self):
        print("you clicked a button")

GUI = CreateGui(root)
GUI.CreateButton("Click Me!", "self.clicker")

root.mainloop()

CodePudding user response:

how about changing command to command=target, and changing the createButton call to GUI.CreateButton("Click Me!", GUI.clicker)

CodePudding user response:

The Command needs to be set when creating each button object

That is not the case.

You can create a button without specifying a command:

self.myButton = Button(self.master, text=lines)

And you can set the command (like many other widget properties) later using dictionary syntax:

self.myButton['command'] = self.clicker
  • Related