全局无法正常工作,并且无法识别变量“文本”吗?

问题描述

全局不能正常工作,它说 即使被声明为text,它也不知道global是什么。

def nguess():
    answer = random.randint ( 1,50 )

def check():
    global attempts
    attempts = 10
    global text
    attempts -= 1

    guess = int(e.get())
    if answer == guess:
        text.set("yay you gat it right")
        btnc.pack_forget()
    elif attempts == 0:
        text.set("you are out of attempts")
        btnc.pack_forget ()
    elif guess > answer:
        text.set("incorrect! you have "+ str(attempts) + "attempts remaining. Go higher")
    elif guess < answer:
        text.set("incorrect! you have "+ str(attempts) + "attempts remaining. Go lower")
    return


nw = tk.Toplevel(app)

nw.title("guess the number")
nw.geometry("500x150")
lable = Label(nw,text="guess the number between 1 - 50")
lable.pack()
e = Entry(nw,width = 40,borderwidth = 10)
e.pack()
btnc = Button(nw,text = "Check",command = check)
btnc.pack()
btnq = Button ( nw,text="Quit",command=nw.destroy )
btnq.pack()
text = StringVar()
text.set("you have ten attempts remaining ")
guess_attempts = Label (nw,textvariable = text)
guess_attempts.pack()

解决方法

好吧,这是在尝试在初始化变量之前获取变量,即在check函数中,您正在调用global text变量,这意味着您要携带任何{ {1}}变量存储在text中,但是问题在于global namespace中尚不存在text变量,因为您是在调用global namespace函数之后创建的。下面我显示一个示例:

check

由于我刚才的解释,这将引发错误,因此您要做的是这样的(基于示例):

def test():
  global variable
  print(variable)

test()
variable = 'Hello'

简而言之,在调用使用def test(): global variable print(variable) variable = 'Hello' test() 的{​​{1}}函数之前,先初始化text变量