如何启用带有多个CheckButton的多个Entrybox?

时间:2019-10-09 17:18:40

标签: python tkinter tkinter-entry tkinter.checkbutton

我正在尝试使用功能将每个单独的按钮链接到特定的输入框。但我不知道如何命名每个单独的按钮。编码对我来说是新的,我迫切需要帮助...

尝试使用在线找到的功能,但只有最后一个输入框受到影响

from tkinter import *

#initialise intial window, root
root = Tk()

dishes = Text(root, cursor="arrow")

qty = Text(root, cursor="arrow")

dishes.pack(side=RIGHT)
qty.pack(side=LEFT)


#to display a entrybox each row
for i in range(10):

    ent = Entry(root, width=3, state='disabled')
    qty.window_create("100.0", window=ent)
    qty.insert("end", "\n")

##to display a checkbutton each row
for key in range(10):

    var = IntVar(value=0)
    cb = Checkbutton(dishes, text="%d" % key,
                     variable=var, onvalue=1, offvalue=0)
    dishes.window_create("end", window=cb)
    dishes.insert("end", "\n")

root.mainloop()

1 个答案:

答案 0 :(得分:1)

您可以将条目和变量保存在数组中,并使用索引引用它们,前提是条目和复选按钮之间存在1:1的关系。

对于条目:

entries = []
for i in range(10):
    ent = Entry(root, width=3, state='disabled')
    entries.append(ent)
    ...

对于checkbutton变量:

vars = []
for key in range(10):
    var = IntVar(value=0)
    vars.append(var)
    cb = Checkbutton(..., command=lambda i=key: set_state(i))
    ...

有关更改状态的命令:

def set_state(i):
    new_state = "disabled" if vars[i].get() == 0 else "normal"
    entries[i].configure(state=new_state)