在 GTK 动作侦听器中操作 python 变量

manipulate python variable inside a GTK action listener

我正在尝试附加到复选框按钮的动作侦听器。我的目标是在复选框为 checked/unchecked 时切换变量值( 0 或 1 )。

我有 C 语言背景,对 python 还很陌生。我也一直在阅读全局变量,但我似乎无法理解它。

我先用 C 做一个例子:

//#includes

int test; //i could say public int test but it is public by default

int foo()
{
    test = 1;
    return test;
}
void main()
{
   test = 0;
   print (foo);
}

下面是一些示例 python 代码。

class someRandomClass: 

    def on_checkbutton1_toggled(self, widget, data=None):
        if test == 0:
            test = 1
        if test == 1:
            test = 0

    def __init__(self):
        global test
        test = 0

if __name__ == "__main__":
    main = someRandomClass()
    gtk.main()

执行此 python 代码并单击复选框会引发 UnboundLocalError:赋值前引用的局部变量'test'

我已经尝试在函数外部创建全局变量,但仍在 class 内部 - 使用与示例 C 代码相同的方法。

我在发布后很快就找到了自己的答案:

def on_checkbutton1_toggled(self, widget, data=None):
    global test
    chkbtn1 = self.builder.get_object("checkbutton1")
    print "BUTTON CHECKED -",chkbtn1.get_active()
    if chkbtn1.get_active() == 0:
        test = 0
    if chkbtn1.get_active() == 1:
        test = 1
    print test

def __init__(self):

    global test 

有了这个,我可以在我的其他听众中打印出 test 的值。如果有人需要更多代码,请随时告诉我。