Python 这是';自我定义不明确';错误是范围问题吗?

Python 这是';自我定义不明确';错误是范围问题吗?,python,oop,Python,Oop,在我的主脚本中,我有以下代码: class Sequence: def __init__(self, colour, text): self.colour = colour self.width = 5 self.height = 5 self.text = text def create_window(self, root): self.name=tk.Label(root,text=self.

在我的主脚本中,我有以下代码:

class Sequence:

    def __init__(self, colour, text):
        self.colour = colour
        self.width = 5
        self.height = 5
        self.text = text

    def create_window(self, root):
        self.name=tk.Label(root,text=self.text, wdith=self.width, height=self.height, 
        bg=self.colour
        self.name.pack()
在我的gui脚本中,此代码作为

Sequence.create_window(self, root)
我得到一个错误:

Sequence.create_window(self, root) NameError: name 'self' is not defined

我真的不知道如何解决这个问题,这与程序的作用域有关吗?

您需要先初始化一个对象:

class Sequence:

    def __init__(self, colour, text):
        self.colour = colour
        self.width = 5
        self.height = 5
        self.text = text

    def create_window(self, root):
        self.name=tk.Label(root,text=self.text, wdith=self.width, height=self.height, 
        bg=self.colour)
        self.name.pack()

sequence = Sequence("blue", "test")
sequence.create_window(root)

root是在create_window方法中定义的变量

tk.Label
需要放置在作为第一个参数传递的窗口或框架中

导入系统 如果sys.version_info.major==2 #对于python 2 将Tkinter作为tk导入 其他的 #对于python 3 将tkinter作为tk导入 类别顺序: 定义初始化(自身、颜色、文本): 颜色 自宽=5 自我高度=5 self.text=文本 def创建_窗口(自,根): self.name=tk.Label(根,text=self.text,wdith=self.width,height=self.height, bg=自身颜色) self.name.pack() 如果名称=“\uuuuu main\uuuuuuuu”: root=tk.tk() 顺序=顺序(“蓝色”、“测试”) 序列。创建_窗口(根) root.mainloop()
请先回顾一下,您需要创建一个
序列的实例。然后您可以调用实例的
create\u window
方法,而无需将
self
作为参数传递。我的意思是,是的,这基本上是因为您试图使用一个未在该范围内定义的变量。如果您有一个函数,
def plus_-two(x):返回x+2
您希望
plus_-two(x)
如何工作?否,它将抛出NameError,因为调用者中没有
x
。但是,你基本上需要理解OOP,这些是类中的方法,类应该首先被实例化。当我这样做的时候,我得到另一个错误,说“根”没有定义。是的,很明显。因为必须先定义root:),但我不知道root是什么。请看一下文档:)