NameError:名称“first”未定义我能做什么?

2024-09-30 10:39:33 发布

您现在位置:Python中文网/ 问答频道 /正文

from tkinter import *
root = Tk()
root.geometry("400x400")
root.title("Bubble Sort")

def printfirst():
    get1 = w.get()
    get2 = e.get()
    get3 = r.get()
    get4 = t.get()
    get5 = y.get()
    first = Label(root, text= get1 + get2 + get3 + get4 + get5)
    first.pack()

def test():
    get1 = w.get()
    get2 = e.get()
    get3 = r.get()
    get4 = t.get()
    get5 = y.get()
    if get1 > get2:
        first.configure(text= get2 + get1 + get3 + get4 + get5)

te = Label(root, text="Enter 5 Diffrent Numbers")
te.pack()
w = Entry(root)
get1 = w.get()
w.pack()
e = Entry(root)
get2 = e.get()
e.pack()
r = Entry(root)
get3 = r.get()
r.pack()
t = Entry(root)
get4 = t.get()
t.pack()
y = Entry(root)
get5 = y.get()
y.pack()
p = Button(root, text="Print Out", command=printfirst)
p.pack()

gg = Button(root, text="Sort It!", command=test)
gg.pack()

root.mainloop()

错误日志:

"Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter__init__.py", line 1533, in call return self.func(*args) File "C:/Users/lycelab18/Desktop/testt.py", line 29, in test first.configure(text= get2 + get1 + get3 + get4 + get5) NameError: name 'first' is not defined"


Tags: textintestgettkinterrootsortpack
3条回答

变量first只存在于函数printfirst()的范围内,这意味着您不能从test()的范围内访问它。你知道吗

解决这个问题的一种方法是从printfirst()函数中return first,保存这个变量,然后在第二个方法中将它作为参数传递;test(first)

这看起来像这样:

def printfirst():
    get1 = w.get()
    get2 = e.get()
    get3 = r.get()
    get4 = t.get()
    get5 = y.get()
    first = Label(root, text= get1 + get2 + get3 + get4 + get5)
    first.pack()
    return first

def test(first):
    get1 = w.get()
    get2 = e.get()
    get3 = r.get()
    get4 = t.get()
    get5 = y.get()
    if get1 > get2:
        first.configure(text= get2 + get1 + get3 + get4 + get5)

first = printfirst()
test(first)

如错误所示,first没有在def test():中定义 您可以像在def printfirst中那样定义和初始化它

def test():
    get1 = w.get()
    get2 = e.get()
    get3 = r.get()
    get4 = t.get()
    get5 = y.get()
    # If this is how you want to initialise it
    first = Label(root, text= get1 + get2 + get3 + get4 + get5)
    first.pack()
    if get1 > get2:
         first.configure(text= get2 + get1 + get3 + get4 + get5)

test()函数中,在定义first变量之前使用first.configure(...)

printfirst()中定义的first值在test()函数中不存在。你知道吗

相关问题 更多 >

    热门问题