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 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)
如果有一个原因,你不希望它是一个方法在你的类,那么你需要重命名变量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)
# ^^^^^^^^^^^^^^^^^