从网格位置获取 Tkinter Checkbutton 值

问题描述

我无法从网格位置获取 tkinter 复选框按钮的开/关状态。在这个基本示例中,如果复选框处于打开状态,我想打印文本,但是我不断收到错误,即 checkbutton 对象没有属性 get,尽管当我单击其中一个复选框时,测试函数会打印“on”或“关闭”就好了。

Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:3000/css/filename.css".
import tkinter as tk

def gui(root):
    root.geometry('150x150')
    root.config(background='sNow3')

    for row in range(5):
        checkBoxVar = tk.Intvar()
        checkBox = tk.Checkbutton(root,text='',variable=checkBoxVar,command= lambda status=checkBoxVar: test(status=status))
        checkBox.select()
        checkBox.grid(row=row,column=1)
        textBox = tk.Text(root,height=1,width=10)
        textBox.grid(row=row,column=2)
    saveBtn = tk.Button(root,text='Save',command=save)
    saveBtn.grid(row=6,column=1)


def save():
    for row in range(5):
        print(root.grid_slaves(row=row,column=2)[0].get('1.0','end-1c'))
        if root.grid_slaves(row=row,column=1)[0].get() == 1:
            print(root.grid_slaves(row=row,'end-1c'))


def test(status):
    if status.get() == 0:
        print('OFF')
    if status.get() == 1:
        print('ON')

if __name__ == '__main__':
    root = tk.Tk()
    gui(root)
    tk.mainloop()

解决方法

即使错误是正确的,您的代码也做对了一切,Checkbutton 没有任何 get() 属性。我认为您正在尝试获取 checkboxVar 的值。但由于函数之间没有联系,我认为不可能在您的代码中获得 Variable 的实例。

因此要解决此问题,您可以将所有 checkboxVar 值保存到列表或字典中以备后用,或者将它们保存到各自的Checkbuttons

...
    for row in range(5):
        checkboxVar = tk.IntVar()
        checkbox = tk.Checkbutton(root,text='',variable=checkboxVar,command=lambda status=checkboxVar: test(status=status))
        checkbox.select()
        checkbox.var = checkboxVar  # SAVE VARIABLE
        checkbox.grid(row=row,column=1)
        textbox = tk.Text(root,height=1,width=10)
        textbox.grid(row=row,column=2)
    saveBtn = tk.Button(root,text='Save',command=save)
    saveBtn.grid(row=6,column=1)
...

稍后可以从 checkbutton 的实例中调用,例如 checkbutton.var.get()。所以这是您的 save() 函数

中的一个小变化
def save():
    for row in range(5):
        print(root.grid_slaves(row=row,column=2)[0].get('1.0','end-1c'))
        if root.grid_slaves(row=row,column=1)[0].var.get():
            print(root.grid_slaves(row=row,'end-1c'))