禁用 Python 和 Tk 中的按钮

disable buttons in Python and Tk

学习组,

我正在开发一个带有一行单选按钮的图形用户界面,必须在 "auto" 模式下将其禁用。

部分脚本:

#  define Auto Manual Mode: 
def AM_procedure():
    global manual
    if vam.get()==1:
        am_mode.set("Auto")
        manual = False 
        for txt,val in space:
            space_button=Radiobutton(root, text = txt, value=val)
            space_button.configure(state = 'disabled')
    else:
        am_mode.set("Manual")
        manual = True
        for txt,val in space:
            space_button=Radiobutton(root, text = txt, value=val)
            space_button.configure(state='normal')
    print manual
    return;

剪... 按钮:

for txt,val in space:
    space_button=Radiobutton(root, text = txt, font=fnt, indicatoron=0, width=8, variable=v, command=ShowChoice,value=val)
    space_button.grid(row=8, column=val-1)

for txt,val in AM:
    am_button=Radiobutton(root, text = txt, font=fnt, indicatoron=0, width=8, variable=vam, command=AM_procedure, value=val)
    am_button.grid(row=9, column=val+1)

Space包含5个元组,AM两个。按下自动按钮应该使第一行变灰。我尝试了几件事,我设法只将最后一个按钮变灰。但是这个脚本没有任何效果。 请指教。 提前致谢, 哈克

像这样创建小部件的问题:

for i in range(10):
    button=Button(root, text = i)
    button.grid(column=i)

是一旦 for 循环完成就没有简单的方法来访问创建的按钮,仍然有一个变量 button 将指向最后创建的小部件,您可以使用 root.winfo_children() 获取根的每个子节点并配置它们:

for w in root.winfo_children():
    w.configure(state="disabled")

但是如果你 运行 在根 window 上这样做,它将禁用你程序中的几乎所有内容。

您真正需要的是保持对您创建的所有按钮的引用:

space_buttons = [] #list of space buttons

...

for txt,val in space:
    space_button=Radiobutton(root, text = txt, font=fnt, indicatoron=0, width=8, variable=v, command=ShowChoice,value=val)
    space_button.grid(row=8, column=val-1)
    #add it to the list of space buttons
    space_buttons.append(space_button)

然后当你想配置它们时,你可以使用:

for button in space_buttons:
    button.configure(state="disabled")

唯一的潜在问题是,如果 space 列表在您的程序中的某个时刻发生变化,在这种情况下,您可能需要一个函数来重新创建按钮:

def create_space_buttons():
    while space_buttons: #same as while len(space_buttons)>0:
        space_buttons.pop().destroy() #remove existing buttons

    for txt,val in space:
        space_button=Radiobutton(root, text = txt, font=fnt, indicatoron=0, width=8, variable=v, command=ShowChoice,value=val)
        space_button.grid(row=8, column=val-1)
        #add it to the list of space buttons
        space_buttons.append(space_button)

可能还有 am_buttons 的类似功能。