为什么代码为我的两个变量提出了NameError?

时间:2018-07-26 08:09:38

标签: python tkinter

单击NEXT按钮后,它将为l3.destroy()NEXT.destroy产生NameError。我想不出为什么说l3NEXT未定义的原因。有人可以看看我的代码并向我解释吗?

#Import tkinter module and random from tkinter module
from tkinter import *
import random
import time

win = Tk()
win.configure(cursor='gumby', bg='yellow')
win.title('A sImPlE gUeSsInG gAmE')
win.wm_iconbitmap('favicon.ico')
number = random.randint(1, 101) #set number as a random integer
f = Frame(win)
#No play button(NO)
def clicked():
    win.destroy()

#Play button (YES)
def clicked1():
    #Erase previous screen
    l.destroy()
    l2.destroy()
    NO.destroy()
    YES.destroy()

    win.title('Are you READY?')
    win.wm_iconbitmap('favicon.ico')
    win.configure(background = "deep sky blue", cursor='rtl_logo')
    f2 = Frame(win)
    l3 = Label(win, text = 'The rule is simple. You have 5 chances to \n guess what number I am thinking of.', bg = 'deep sky blue', fg = 'yellow', font=('Snap ITC', 20))
    l3.grid(row = 1, column = 4, columnspan=5)

    #'Next' button
    NEXT = Button(win, text = 'NEXT', command=clicked2)
    NEXT.grid(row = 5, column = 5)


#NEXT button command
def clicked2():
    win.title('Are you READY?')
    win.wm_iconbitmap('favicon.ico')
    win.configure(background = "deep sky blue", cursor='rtl_logo')
    f3 = Frame(win)
    l3.destroy() #NameError: name 'l3' is not defined <------------------
    NEXT.destroy()#NameError: name 'NEXT' is not defined <------------------
    l4 = Label(win, text = 'I am thinking of a number between 1 to 100.\n Good Luck!', bg = 'deep sky blue', fg = 'yellow', font=('Snap ITC', 20))
    l4.grid(row = 1, column = 3, columnspan=5)
    BEGIN = Button(win, text ='BEGIN')
    BEGIN.grid(row = 4, column = 4)

#Intro
l = Label(win, text = "Welcome to a number game child.", font=('Snap ITC', 20), bg='yellow', fg='slateblue')
l2 = Label(win, text = "Would you like to play?", font=('Snap ITC', 20), bg = 'yellow', fg='slateblue')
l.grid(row = 1, column = 3, columnspan=3)
l2.grid(row = 2, column = 3, columnspan=3)

#Play or not buttons(YES/NO)
NO = Button(win, text = 'NO', command=clicked)
NO.grid(row = 4, column = 3)
YES = Button(win, text = 'YES', command=clicked1)
YES.grid(row = 4, column = 4)

1 个答案:

答案 0 :(得分:0)

使用全局变量的函数需要将每个变量显式声明为全局变量。例如:

n = 2

def foo():
    n += 1

foo()
print(n) # Prints: 2

添加global n将解决问题

n = 2

def foo():
    global n
    n += 1

foo()
print(n) # Prints: 3