我正在使用Tkinter来创建游戏,但遇到第一个窗口时,却收到此错误UnboundLocalError:在分配前引用了局部变量'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)
答案 0 :(得分:0)
当您尝试为外部作用域中的变量分配新值时,您需要在函数内添加global关键字。
在上面的示例中,当您将num传递给场景_1_0(..)函数时,num将被视为局部变量。在情境_1_0()中,您定义了对另一个函数情境_1_1()的调用,该函数试图为全局变量分配新值,因此会出现错误:local variable 'x' referenced before assignment
。在函数场景_1_1()中使用全局变量可以解决您的错误
您可以在以下示例示例中进行检查:
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)
locals()和globals()字典可以帮助查看存在哪些变量