【发布时间】:2021-12-21 18:31:06
【问题描述】:
我正在尝试选中一个复选框并使用上方按钮删除“复选框”和“标签”。它们都是从同一个列表中循环创建的。 我试图建立一个字典,以“按钮”为键,以“result_of_checkboxes”为值,如果值与“”不同,则销毁键。这是行不通的。如果按钮是钥匙,为什么我不能破坏它们?什么是正确的方法? 提前致谢!
from tkinter import *
root = Tk()
root.geometry('400x400')
def destroy_button():
for key, value in dict_check_and_buttons:
if value != '' and current_var != '':
key.destroy()
current_box.destroy()
my_friends = ['Donald', 'Daisy', 'Uncle Scrooge']
button1= tk.Button(root, text = "delete both if cbox is checked", command = destroy_button).pack()
#-----ild checkbuttons and store results in checkbutton_result list
checkbutton_result = []
for index, friend in enumerate(my_friends):
current_var = tk.StringVar()
current_box = tk.Checkbutton(root, text= friend,
variable = current_var,
onvalue = friend, offvalue = ""
)
checkbutton_result.append(current_var) #append on and off results
current_box.pack()
#-----build buttons and store them in buttons_list
buttons_list = []
for index, friend in enumerate(my_friends):
buttons= tk.Button(root, text = friend).pack()
buttons_list.append(buttons)
#-----build a dict with list to say "if onvalue != '' destroy button"
dict_check_and_buttons = dict(zip(buttons_list, checkbutton_result))
root.mainloop()
错误是:
Exception in Tkinter callback
Traceback (most recent call last):
File "c:\python\python38\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "<ipython-input-18-954d3a090f2c>", line 7, in destroy_button
for key, value in dict_check_and_buttons:
TypeError: cannot unpack non-iterable NoneType object
【问题讨论】:
-
您的
buttons_list只是一个包含Nones 的列表——调用.pack()的结果,而不是小部件本身。您需要单独执行.pack(),就像您在checkbutton_result循环中所做的一样。
标签: python for-loop tkinter checkbox destroy