0

I am writing a function that get called when I click a button, but before calling this function, I would like to change a class variable.

How do you do that in a button ? As now I did declare the button as following:

calculatebutton = Button(self, text="run function", command=self.calculate_total(self.totals))
calculatebutton.place(x=150, y=600)

This run my function, but I want to change also a class variable, and I want to change it before I run the function.

  • 1
    `command= lambda q = self.totals : self.calculate_total(q)` if not work : define `q` before binding to button. `q = self.totals; command= lambda : self.calculate_total(q)`. Last change required last values otherwise always processing a static value. – dsgdfg Dec 30 '16 at 07:20
  • 1
    `command` expects function name without `()` so now your `calculate_total()` is executed at start and its result is assigned to `command` as function name. If `calculate_total()` returns `None` then you have `comman=None`. You can use `lambda` to assign correctly function with arguments. – furas Dec 30 '16 at 08:17

1 Answers1

1

You can wrap your method with new one and in it, before calling your method, you can do whatever you want.

def wrapper(self):
    self.your_value = new_value
    self.calculate_total(self.totals)

calculatebutton = Button(self, text="run function", command=self.wrapper)
calculatebutton.place(x=150, y=600)

Also note that, if you want to pass an argument to your method when calling from button, you should use lambdas.

Community
  • 1
  • 1
Lafexlos
  • 7,618
  • 5
  • 38
  • 53