pam
pam

Reputation: 113

python - global name <function> is not defined

How do you use a method from the same class in this case? I am trying to make a tkinter scale that will update every time it is changed. How do I collect this value?

This is a snippet of the code

For example,

class Humidity(Page):

   humidityValue = 0

   def __init__(self, *args, **kwargs):
      Page.__init__(self, *args, **kwargs)
      container = tk.Frame(self)
      container.pack(side="top", expand =True, fill = "both")

      humidityScale = tk.Scale(container, from_=0, to=60, tickinterval=10, width= 30,
                             orient="horizontal", borderwidth = 0, highlightthickness= 0, length=800, command=set_humidity)
      humidityLabel = tk.Label(container, text="Humidity(%)" , fg='White')
      humidityScale.pack(side="top")                            
      humidityScale.set(25)                                    #Sets humidity values to 25%
      humidityLabel.pack(side="bottom")
      humidityValue = humidityScale.get()

   def get_humidity(self):
      print self.humidityValue

   def set_humidity(val):
      humidityValue = val         

Will return an error saying : global name 'set_humidity' is not defined

Upvotes: 0

Views: 746

Answers (1)

TerryA
TerryA

Reputation: 59974

You forgot to add self. behind humidityValue when you were declaring the attributes in your __init__:

humidityValue = humidityScale.get() should be self.humidityValue = humidityScale.get().

This is needed so that both objects created using your class AND functions inside the class (as you have witnessed) can self-reference attributes.

You probably will need to do the same changes to other variables in your __init__ (eg humidityScale, humidityLabel).


In regards to why your function set_humidity doesn't work - you forgot to add self as the first parameter of the function, just like you've done with get_humidity

Upvotes: 1

Related Questions