Python 如何在n次单击后禁用所有单选按钮?
我正在做一个问答式的节目,我在节目中增加了一个额外的问题,这与其他问题不同。这里有8个按钮,问题是: 使用给定选项中的四个按钮弹出列表“lst”中的所有元素 按钮包括:Python 如何在n次单击后禁用所有单选按钮?,python,tkinter,radio-button,Python,Tkinter,Radio Button,我正在做一个问答式的节目,我在节目中增加了一个额外的问题,这与其他问题不同。这里有8个按钮,问题是: 使用给定选项中的四个按钮弹出列表“lst”中的所有元素 按钮包括: ["lst", "while", "for", "i", ":", "lst.pop()", "in", "range(lst)"] 我想做的是在单击每个按钮后禁用它,和在单击4次后禁用所有按钮 我还想知道,我如何检查点击的顺序是否正确 我创建了一个函数,可以禁用带有索引“index”的按钮 def禁用(按钮、索引、单词):
["lst", "while", "for", "i", ":", "lst.pop()", "in", "range(lst)"]
我想做的是在单击每个按钮后禁用它,和在单击4次后禁用所有按钮
我还想知道,我如何检查点击的顺序是否正确
我创建了一个函数,可以禁用带有索引“index”的按钮
def禁用(按钮、索引、单词):
按钮[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'
Tkinter回调中出现异常
回溯(最近一次呼叫最后一次):
文件“/usr/lib/python3.6/tkinter/_init__.py”,第1705行,在调用中__
返回self.func(*args)
文件“”,第340行,在
按钮=按钮(root,text=n,command=lambda index=index,n=n:disable(按钮,index,n)).pack(side='left')
文件“”,第353行,禁用
按钮[index].config(state=“disabled”)
AttributeError:“非类型”对象没有属性“配置”
更改此选项:
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()
我相信索引是一种内置的方法