在回调中看不到全局变量-如何创建这样的函数? [关闭]

问题描述 投票:-3回答:2

我正在尝试创建一个回调函数,其中包含来自另一个可能是全局上下文的值。

我有一个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)
python tkinter
2个回答
0
投票

如果x是全局值,为什么需要将其传递给某种方法?您是否可以像这样访问它:

def somemethod():
    global x #signifies x can be found in the global scope
    #write to a config file


0
投票

声明全局变量时,可以在代码中的任何位置使用它。

[请注意,如果要修改它,则必须使用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了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.