简体   繁体   中英

Why does the code come up with a NameError for two of my variables?

After clicking the NEXT button, it produces a NameError for l3.destroy() and NEXT.destroy . I couldn't think of a reason why it says that l3 and NEXT is undefined. May someone have a look at my code and explain it to me?

#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)

Functions that use global variables need to declare each variable as global explicitly. For example:

n = 2

def foo():
    n += 1

foo()
print(n) # Prints: 2

Adding global n will solve the problem

n = 2

def foo():
    global n
    n += 1

foo()
print(n) # Prints: 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM