gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:56 24 4
gpt4 key购买 nike

我正在使用 Tkinter 创建游戏,尽管我已经将 num 设置为全局变量,但当我经过第一个窗口时,我收到此错误 UnboundLocalError:赋值前引用的局部变量 '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)

最佳答案

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

在上面的示例中,当您将 num 传递给情况_1_0(..) 函数时,num 将被视为局部变量。在situation_1_0()中,您定义了对另一个函数situation_1_1()的调用,该函数尝试为全局变量分配新值,因此您会收到错误:赋值前引用了局部变量“x”。在函数itunes_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() 字典可以帮助查看存在哪些变量

关于python - 我收到 'num' 的 UnboundLocalError,但我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58392586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com