matplotlib - Python: pass variable name to function to change value? -


i created tkinter window. in 1 frame, use matplotlib plot text (i use matplotlib because need greek math charakters). have more 10 variables , 2 buttons each variable change value of it. so, thought instead of have 28 functions change values, write 2 functions, change desired variable using exec(). not work...

previous attempt variable a:

def ap():     global     a+=10     plot()     canvas.draw()  def am():     global     a-=10     plot()     canvas.draw()  button_ap = tk.button(configframe, text='a+', command=ap).grid(row=0,column=0) button_am = tk.button(configframe, text='a-', command=am).grid(row=0,column=1) 

this works. press 1 of buttons, plot updated new value of a.

new attempt:

def parp(var):     exec('global '+var)     exec(var+'+=10')     plot()     canvas.draw()  def parm(var):     exec('global '+var)     exec(var+'-=10')     plot()     canvas.draw()  button_ap = tk.button(configframe, text='a+', command=lambda: parp('a')).grid(row=0,column=0) button_am = tk.button(configframe, text='a-', command=lambda: parm('a')).grid(row=0,column=1) 

this not work. read variable , executes 'var+=10', because if print variable afterwards, reduced 10. plot() command not update plot.

do have idea why? thx.

to able manipulate global variables exec in function need provide global() 2nd argument exec.

here how use ecec on globals():

a = 0 b = 10 c = 20  def parp(my_var):     exec("{} -= 10".format(my_var), globals())  parp("a") parp("b") parp("c")  print(a) print(b) print(c) 

one other thing. avoid using + or % combining strings. instead use format() current preferred method function.

because myself , others "globals bad mkay!".

here link explanation why.

here class same thing use of class attributes not need use globals.

class execclass():       def __init__(self):         self.a = 0         self.b = 10         self.c = 20          self.parp("a")         self.parp("b")         self.parp("c")          print(self.a, self.b, self.c)      def parp(self, my_var):         exec("self.{} -= 10".format(my_var))   my_class = execclass() 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -