从函数调用时自己不工作

Self not Working while calling from function

def lbl():
    lbl1=Label(self,text='hello',fg='red').place(x=10,y=10) 

class login(Frame):
        global self
        def __init__(self,parent,controller):
                Frame.__init__(self,parent)
                btn=Button(self,text='view',command=lbl).place(x=40,y=40)

现在在上面的函数中出现了名称 self 未定义的错误

如果您希望 lbl 能够访问 self,它应该是您 class 上的一个方法。

class login(Frame):
    def __init__(self, parent,controller):
        ...
        btn=Button(self,text='view',command=self.lbl).place(x=40,y=40)
        #                                   ^^^^^
    def lbl(self):
        lbl1=Label(self,text='hello',fg='red').place(x=10,y=10) 

如果您出于某种原因不希望它成为 class 上的一个方法,那么您需要重命名该函数内的变量 self,并让该函数接受一个标识标签父级的参数:

def lbl(parent):
    #   ^^^^^^
    lbl1=Label(parent,text='hello',fg='red').place(x=10,y=10) 
    #          ^^^^^^


class login(Frame):
    def __init__(self, parent,controller):
        ...
        btn=Button(self,text='view',command=lambda: lbl(self)).place(x=40,y=40)
        #                                   ^^^^^^^^^^^^^^^^^