0

I tried to make a function which create a button with a command (action) on a window but I can't specify a self variable.

The function :

    def addButton(self,text,row,column,pady,action):

    action = "Window."+str(action)
    print(action)
    button = Button(self.Window, text=str(text), command=lambda:exec(action))
    button.grid(row=int(row),column=int(column),pady=int(pady),sticky=EW)
    self.buttons.append(button)

I'll be grateful if someone can help me

1
  • getattr is your friend: docs.python.org/3/library/functions.html#getattr. Your question is unclear, so I can't help tell you exactly what to do, but you can use getattr to retrieve the callable object that you want to be your action. It would look something like: action_obj = getattr(Window, action) Commented Dec 5, 2019 at 22:26

1 Answer 1

2

For any python object you can use getattr to get an attribute by name. In your case you could use something like this:

func = getattr(self.Window, action)
button = Button(..., command = func)

There's no need to use exec, since in this case getattr will return a reference to a function (a callable), and the command attribute requires a reference to a function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.