我正在使用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)发布于 2019-10-15 19:13:42
当您尝试将新值赋给外部作用域中的变量时,需要在函数中添加全局关键字。
在上面的示例中,当您将num传递给situation_1_0(..)函数,num将被视为局部变量。在situation_1_0()中,您定义了对另一个函数situation_1_1()的调用,该函数尝试为全局变量分配一个新值,因此您会得到一个错误:local variable 'x' referenced before assignment。在函数situation_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()字典可以帮助查看存在哪些变量
https://stackoverflow.com/questions/58392586
复制相似问题