【问题标题】:Self not Working while calling from function [closed]从函数调用时自我不工作[关闭]
【发布时间】:2021-12-09 07:37:38
【问题描述】:
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)

现在在上面的函数中,它给出了 name self is not defined 的错误

【问题讨论】:

标签: python python-3.x class oop tkinter


【解决方案1】:

如果你想让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)
        #                                   ^^^^^^^^^^^^^^^^^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多