我试图让我的方法组装按钮取决于" list"我选择, 这样做的最佳方法是什么?
frame = Frame(root)
frame.grid()
b1 = Button(frame, textvariable='1')
a1 = b1.grid(row=4, column=0, sticky='w')
b2 = Button(frame, text='2')
a2 = b2.grid(row=5, column=0, sticky='w')
b3 = Button(frame, text='3')
a3 = b3.grid(row=6, column=0, sticky='w')
b4 = Button(frame, text='4')
a4 = b4.grid(row=7, column=0, sticky='w')
b5 = Button(frame, text='5')
a5 = b5.grid(row=8, column=0, sticky='w')
b6 = Button(frame, text='6')
a6 = b6.grid(row=4, column=2, sticky='e')
b7 = Button(frame, text='7')
a7 = b7.grid(row=5, column=2, sticky='e')
b8 = Button(frame, text='8')
a8 = b8.grid(row=6, column=2, sticky='e')
b9 = Button(frame, text='9')
a9 = b9.grid(row=7, column=2, sticky='e')
b10 = Button(frame, text='10')
a10 = b10.grid(row=8, column=2, sticky='e')
butt_list = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10]
mainloop()
基本上,我希望能够只显示一定数量的这些按钮,或者从列表中检索它们,而不是一次性将它们全部删除
答案 0 :(得分:3)
发表评论后,我建议您将按钮存储在列表中(正如您所做)并创建一个"网格映射字典"这会将您的网格名称映射到请求按钮的索引。
grid = {}
grid[1] = [1, 5, 9]
然后,如果你想显示给定网格选项的按钮,只需访问字典中的网格键并循环按钮:
def buttons_for_grid(key):
return [buttons[button] for button in grid[key]]
代码转换为"给我存储在网格字典中的索引的所有按钮对象"。
答案 1 :(得分:1)
由于文本是唯一不同的东西,你可以跟踪你想要显示的文本(如果你也想要一个不同的命令=每个按钮,你可以跟踪[text,command / callback]的子列表)。
from tkinter import *
root = Tk()
frame = Frame(root)
frame.grid()
list_of_text=["1", "3" , "5", "6", "7"]
r=4
c=0
stick="w"
for num in list_of_text:
## grid on same line since you don't reference the button again
Button(frame, text=num).grid(row=r, column=c, sticky=stick)
r += 1
if r > 7:
r=4
c += 1
stick="e"
root.mainloop()