首页 > 解决方案 > 这个“自我未定义”错误是范围问题吗?

问题描述

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

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

我不确定如何解决这个问题,它与程序的范围有关吗?

标签: pythonoop

解决方案


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

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)

推荐阅读