我正在尝试创建一个回调函数,其中包含来自另一个可能是全局上下文的值。
我有一个tkinter条目,我从我认为是全局变量的值中得到了一个值然后将其传递给方法,这样:
#x should be global
txtBlah=tk.Entry(mywin, width=50)
#x is global, or should be
x=txtBlah.get()
确定,现在需要去这里
def somemethod(someval):
#write to a config file
并且该方法被这样调用:
cmd_settings = tk.Button(window, command = somemethod)
我试图做这样的事情,但不行:
somemethod(x)
如果x是全局值,为什么需要将其传递给某种方法?您是否可以像这样访问它:
def somemethod():
global x #signifies x can be found in the global scope
#write to a config file
?
声明全局变量时,可以在代码中的任何位置使用它。
[请注意,如果要修改它,则必须使用global
关键字在您的范围内声明它,如下所示:
my_global_var = 0 # Global variable
def do_something():
my_new_variable = my_global_var # This is fine
def do_something_else():
global my_global_var # You must use the global keyword if you wanna modify the variable
my_global_var = 1 # This is also fine
def do_one_more_thing():
my_global_var = 2 # This will throw an UnboundLocalError error
您也可以参考this question了解更多信息。