Tkinter 获取 CheckButton 的选定值

Sab*_*san 0 python tkinter python-2.7

我已经尝试了stackoverflow 中的几个示例,但不幸的是对我不起作用。

我只想获取 Tkinter、Python 选定的 checkButton 的值。

我有一个 CheckButton 列表,如下所示

## csv file has rows like
# 101, apple
# 102, orange
for row in csvReader:
        checkButton = Checkbutton(top, text = row[1], variable = StringVar(), 
                 onvalue = row[0], offvalue = "0", height=2, \
                 width = 0, justify=Tkinter.LEFT)
        checkButton.pack()
        checkBoxList.append(checkButton)
Run Code Online (Sandbox Code Playgroud)

单击表单中的按钮时,这里是需要获取复选框的选中值的回调。

def btnStartCallBack():
    for chkBox in checkBoxList:
        print chkBox.variable().get()
        # also tried below
        # print chkBox.get()
        # print chkBox.var()
        # print chkBox.onvalue.get()
Run Code Online (Sandbox Code Playgroud)

它返回:

AttributeError: Checkbutton instance has no attribute 'variable'
Run Code Online (Sandbox Code Playgroud)

我只是想知道是否可以在选择 CheckButton 时获取其值。我应该在哪个属性上寻找这个?

cjo*_*318 5

我通常在课堂上制作 GUI,例如http://zetcode.com/。我会做类似的事情

self.v = StringVar()
self.cb1 = CheckButton( self, text=row[1], variable=self.v )
Run Code Online (Sandbox Code Playgroud)

然后后来..

self.v.get()
Run Code Online (Sandbox Code Playgroud)

我认为您可能需要variable在代码中进行不同的声明。祝你好运!