简体   繁体   English

python-全局名称 <function> 没有定义

[英]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. 我正在尝试制作一个tkinter刻度,每次更改时都会更新。 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 将返回错误消息:未定义全局名称“ set_humidity”

You forgot to add self. 你忘了加self. behind humidityValue when you were declaring the attributes in your __init__ : __init__中声明属性时,在humidityValue后面:

humidityValue = humidityScale.get() should be self.humidityValue = humidityScale.get() . humidityValue = humidityScale.get()应该是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 ). 您可能需要对__init__其他变量进行相同的更改(例如humidityScale __init__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 关于为什么函数set_humidity不起作用的原因-您忘记将self作为函数的第一个参数添加,就像使用get_humidity所做的get_humidity

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM