NameError: name 'top' is not defined

NameError: name 'top' is not defined

我正在尝试使用 Tkinter 创建一个 GUI,代码是:

from tkinter import * 

class LoginFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)   

        self.parent = parent        
        self.initUI()

    # initialize the login screen UI  
    def initUI(self):
        self.parent.title("Login Screen")

        # create a menu bar
        menubar = Menu(top)

        # create a help menu
        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", command=about)
        menubar.add_cascade(label="Help", menu=helpmenu)

        # display the menu
        self.parent.config(menu=menubar)


#----------------------------------------------------------------------
def about():
    """about info"""
    print("This is a Tkinter demo")


# create a button 
#----------------------------------------------------------------------
def make_button(parent, command, caption=NONE, side=top, width=0, **options): # name error 'top' is not defined
    """make a button"""
    btn = Button(parent, text=caption, command=command)

    if side != top:
        btn.pack(side=side)
    else:
        btn.pack()    

    return btn
def main():
    top = Tk()

    # Set up login frame properties 
    top.title("Login Screen")

    # create a login button
    login_btn = make_button(top, about, "Login")

    top.mainloop()


if __name__ == '__main__':
    main()  

我尝试 运行 代码,python 给了我以下错误:

builtins.NameError: name 'top' is not defined

您指的是 make_button 参数列表中的顶部 - 您说的是 side=top,但实际上并未在该函数之前定义 top。没有全局调用top.

在定义之前,您不能将其设置为参数的默认值。

你只在main中定义了top,没有在全局范围内定义,即使是在全局范围内,你在make_button之后定义了; Python 中的默认参数在定义时计算一次,而不是在调用时查找。

最好的方法可能是将大部分函数变成 class 方法,并让 class 本身创建一个 top 属性。

但目前,您可以做一个极简主义的改变:

# Use None as a default at definition time, since top doesn't exist yet
def make_button(parent, command, caption=NONE, side=None, width=0, **options):
    """make a button"""
    if side is None:  # Convert None to top at call time
        side = top
    btn = Button(parent, text=caption, command=command)

    if side is not top:  # Minor tweak: Use identity test over equality
        btn.pack(side=side)
    else:
        btn.pack()    

    return btn

def main():
    global top  # Make top a global then define it
    top = Tk()

    ... rest of main ...

请注意,这仍然不是很好的代码;没有 main 被执行,就没有 top 全局定义,所以你的代码只能用作主程序,而不是没有很多 hackery 的可导入模块。

我也遇到了同样的错误,但我意识到,我需要为 "TOP" 使用大写而不是 "Top",在我使用大写之后,它对我有用。

frame = Frame(root)
frame.pack()


root.title("Calcu_Displayframe")

num_1=StringVar()

topframe = Frame(root)
topframe.pack(side=TOP)

txtDisplay=Entry(frame, textvariable=num_1, bd=20, insertwidth=1, font=30)
txtDisplay.pack(side=TOP)

root.mainloop()

如果你像这样导入 tkinter : import tkinter as tk 那么包将是 test.pack(tk.TOP)

如果你像这样导入 tkinter : from tkinter import * 然后将是 test.pack(TOP)