如何在 Tkinter 中为循环中创建的相同按钮提供唯一名称?
How can I give identical buttons created in a loop unique names in Tkinter?
我使用循环在将它们组织成网格的较大框架内的框架内创建了 3 个空白按钮(因此我可以使用尺寸而不是高度和宽度使它们具有精确的大小)。这些按钮都显示正常但后来在程序中我想单独更改文本但是因为它们没有唯一的名称我不能使用配置。
这是创建代码的按钮:
frameNames = ["A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4", "C1", "C2", "C3", "C4"]
while buttonNumber <= 11:
frameN = frameNames[buttonNumber]
frame = tkinter.Frame(buttonFrame, width=100, height=100)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)
frame.grid_propagate(0)
if "A" in frameN:
frame.grid(row = 0)
elif "B" in frameN:
frame.grid(row = 1)
elif "C" in frameN:
frame.grid(row = 2)
if "1" in frameN:
frame.grid(column = 0)
elif "2" in frameN:
frame.grid(column = 1)
elif "3" in frameN:
frame.grid(column = 2)
elif "4" in frameN:
frame.grid(column = 3)
frame.grid(padx = 25, pady = 25)
button = tkinter.Button(frame, text = " ", bg = "Blue").grid(sticky="nsew")
buttonNumber += 1
window.mainloop()
如果您需要更多信息,请告诉我
谢谢
您可以使用字典来存储创建的按钮,并使用单元格位置或名称(来自frameNames
)作为键:
frameNames = ["A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4", "C1", "C2", "C3", "C4"]
buttons = {} # dictionary to hold the buttons
for name in frameNames:
row = ord(name[0]) - ord("A")
col = int(name[1]) - 1
frame = tk.Frame(buttonFrame, width=100, height=100)
frame.grid(row=row, column=col, padx=25, pady=25)
btn = tk.Button(frame, bg="blue")
btn.place(relwidth=1, relheight=1)
buttons[row,col] = btn # or buttons[name] = btn
然后您可以使用键 row,col
访问特定按钮,例如buttons[0,0]
.
我使用循环在将它们组织成网格的较大框架内的框架内创建了 3 个空白按钮(因此我可以使用尺寸而不是高度和宽度使它们具有精确的大小)。这些按钮都显示正常但后来在程序中我想单独更改文本但是因为它们没有唯一的名称我不能使用配置。 这是创建代码的按钮:
frameNames = ["A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4", "C1", "C2", "C3", "C4"]
while buttonNumber <= 11:
frameN = frameNames[buttonNumber]
frame = tkinter.Frame(buttonFrame, width=100, height=100)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)
frame.grid_propagate(0)
if "A" in frameN:
frame.grid(row = 0)
elif "B" in frameN:
frame.grid(row = 1)
elif "C" in frameN:
frame.grid(row = 2)
if "1" in frameN:
frame.grid(column = 0)
elif "2" in frameN:
frame.grid(column = 1)
elif "3" in frameN:
frame.grid(column = 2)
elif "4" in frameN:
frame.grid(column = 3)
frame.grid(padx = 25, pady = 25)
button = tkinter.Button(frame, text = " ", bg = "Blue").grid(sticky="nsew")
buttonNumber += 1
window.mainloop()
如果您需要更多信息,请告诉我 谢谢
您可以使用字典来存储创建的按钮,并使用单元格位置或名称(来自frameNames
)作为键:
frameNames = ["A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4", "C1", "C2", "C3", "C4"]
buttons = {} # dictionary to hold the buttons
for name in frameNames:
row = ord(name[0]) - ord("A")
col = int(name[1]) - 1
frame = tk.Frame(buttonFrame, width=100, height=100)
frame.grid(row=row, column=col, padx=25, pady=25)
btn = tk.Button(frame, bg="blue")
btn.place(relwidth=1, relheight=1)
buttons[row,col] = btn # or buttons[name] = btn
然后您可以使用键 row,col
访问特定按钮,例如buttons[0,0]
.