我收到'num'的UnboundLocalError,我不知道为什么

2024-06-25 23:52:36 发布

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

我正在使用Tkinter创建一个游戏,我在通过第一个窗口时,在赋值之前引用了局部变量'num',但我已经将num设置为全局变量。我本来想用我的函数来实现它,但是tkinter不允许我这么做,并且给了我一个错误

 from tkinter import *

 global num
 num = 1.0



 def situation_1_1():
    if num == 1.0:
       window10.destroy()
       num = 1.1


   global window11
   window11 = Tk()
   window11.title( " " )
   window11.resizable( 0, 0 )

   img1 = PhotoImage( file = "img_1_0.png" )



   Img_1 = Label( window11, image = img1)

   Label_1 = Label( window11, relief = "groove", width = 50 )

   Btn_1 = Button( window11, text = "Look around", command = situation_1_1)
   Btn_2 = Button( window11, text = "Go out front", command = situation_1_2)



   Img_1.grid( row = 1, column = 1, rowspan = 75, columnspan = 75 )

   Label_1.grid( row = 1, column = 76, rowspan = 50, columnspan = 100, padx = ( 10, 10 ) )

   Btn_1.grid( row = 61, column = 76, columnspan = 50 )
   Btn_2.grid( row = 61, column = 126, columnspan = 50 )



   Label_1.configure( text = """ """ )

   window11.mainloop()



def situation_1_0(num):
   num = 1.0
   global window10
   window10 = Tk()
   window10.title( " " )
   window10.resizable( 0, 0 )

   img1 = PhotoImage( file = "img_1_0.png" )



   Img_1 = Label( window10, image = img1)

   Label_1 = Label( window10, relief = "groove", width = 50 )

   Btn_1 = Button( window10, text = "Explore the house", command = situation_1_1)
   Btn_2 = Button( window10, text = "Go round back", command = situation_1_2)



   Img_1.grid( row = 1, column = 1, rowspan = 75, columnspan = 75 )

   Label_1.grid( row = 1, column = 76, rowspan = 50, columnspan = 100, padx = ( 10, 10 ) )

   Btn_1.grid( row = 61, column = 76, columnspan = 50 )
   Btn_2.grid( row = 61, column = 126, columnspan = 50 )


   Label_1.configure( text = """ """)

   window10.mainloop()


situation_1_0(num)

Tags: textimgcolumnbuttonnumlabelcommandgrid
1条回答
网友
1楼 · 发布于 2024-06-25 23:52:36

当您尝试为外部作用域中的变量指定新值时,需要在函数中添加全局关键字

在上面的示例中,当您将num传递给情况_1_0(..)函数时,num将被视为局部变量。在情境_1_0()中,您定义了对另一个函数情境_1_1()的调用,该函数试图为全局变量分配一个新值,因此您得到一个错误:local variable 'x' referenced before assignment。在函数中使用全局变量应该可以解决您的错误

您可以使用以下示例检查相同的情况:

global num
num = 1.0

def bar():
    print(locals())
    global num
    if num == 1.0:
        num = 1.4
        print('num value withing bar fn: ', num)
# function to perform addition 
def foo(num):
    print(locals())
    bar()    
    print('num value within foo fn: ', num) 

# calling a function 
foo(num)
print('global num value: ', num)

本地人();globals()字典可以帮助查看存在哪些变量

相关问题 更多 >