【问题标题】:How do I make all Radio Buttons disabled after n clicks?单击n次后如何禁用所有单选按钮?
【发布时间】:2020-03-07 08:10:58
【问题描述】:

我正在制作一个测验类型的程序,其中我添加了一个与其他问题不同的奖励问题。在这里,你有 8 个按钮,问题是:

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

按钮是:

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

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

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

我创建了一个禁用索引为“索引”的按钮的函数

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'

【问题讨论】:

    标签: python tkinter radio-button


    【解决方案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 是一种内置方法。

    【讨论】:

      猜你喜欢
      • 2011-08-19
      • 2019-09-23
      • 2012-04-05
      • 2015-01-12
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多