单击n次后如何禁用所有单选按钮?

时间:2019-11-11 16:01:13

标签: python tkinter radio-button

我正在制作一个测验型程序,在其中添加了一个奖励问题,该问题不同于其他问题。在这里,您将获得8个按钮,问题是:

  

使用给定选项中的四个按钮来弹出列表“ lst”中的所有元素

按钮为:

["lst", "while", "for", "i", ":", "lst.pop()", "in", "range(lst)"]

我想做的是单击后禁用每个按钮,单击4次后禁用所有按钮。

我还想知道,如何检查点击顺序是否正确?

我创建了一个禁用带有索引“ index”的按钮的功能

def disable(buttons, index, word):
    buttons[index].config(state="disabled")

然后我在一个循环上创建了8个按钮。

words=["lst", "while", "for", "i", ":", "lst.pop()", "in", "range(lst)"]
buttons = []
for index in range(8): 
    n = words[index]
    button = Button(root, text = n, command = lambda index = index, n = n: disable(buttons, index, n)).pack(side = 'left')
    buttons.append(button)

这是显示的错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "<ipython-input-163-f56fc3dd64da>", line 340, in <lambda>
    button = Button(root, text = n, command = lambda index = index, n = n: disable(buttons, index, n)).pack(side = 'left')
  File "<ipython-input-163-f56fc3dd64da>", line 353, in disable
    buttons[index].config(state="disabled")
AttributeError: 'NoneType' object has no attribute 'config'

1 个答案:

答案 0 :(得分:1)

更改此:

for index in range(8):
    n = words[index]
    button = Button(root, text = n, command = lambda index = index, n = n: disable(buttons, index, n)).pack(side = 'left')
    buttons.append(button)

对此:

for index in range(8): 
    n = words[index]
    button = Button(root, text = n, command = lambda index = index, n = n: disable(buttons, index, n))
    button.pack(side = 'left')
    buttons.append(button)

您看到的问题是由于在创建按钮的同一行上使用了几何管理器pack()。当所有几何图形管理器都返回None时,如果您尝试编辑按钮,则会收到该错误。

那表示如果您这样编写循环,可能会更好:

# Use import as tk to avoid any chance of overwriting built in methods.
import tkinter as tk

root = tk.Tk()
words = ["lst", "while", "for", "i", ":", "lst.pop()", "in", "range(lst)"]
buttons = []

# Use the list to set index.
for ndex, word in enumerate(words):
    # Append the button object to the list directly
    buttons.append(tk.Button(root, text=words[ndex]))
    # Us the lambda to edit the button in the list from the lambda instead of a new function.
    # A useful trick is to use `-1` to reference the last index in a list.
    buttons[-1].config(command=lambda btn=buttons[-1]: btn.config(state="disabled"))
    buttons[-1].pack(side='left')

if __name__ == '__main__':
    root.mainloop()

我相信index是内置方法。

相关问题