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

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


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



小唯快跑啊
浏览 178回答 1
1回答

繁星淼淼

使用全局变量的函数需要将每个变量显式声明为全局变量。例如:n = 2def foo():&nbsp; &nbsp; n += 1foo()print(n) # Prints: 2添加global n将解决问题n = 2def foo():&nbsp; &nbsp; global n&nbsp; &nbsp; n += 1foo()print(n) # Prints: 3
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python