我试图这样做,以便一旦我将动态按钮放入我这一代的行和列中,它将自动为每个按钮分配一个名称。例如,第1行(A),第1列将是A1。
from tkinter import *
from functools import partial
root = Tk()
def redClick(button_num):
list_of_buttons[button_num].configure(bg="red")
def buttonsMake():
ctr = 0 ## button number / offset number in the list
for columns in range(10):
for rows in range(3):
movieSeats=Button(root, text="Empty", bg="green", fg="white",
width=5, height=1, command=partial(redClick, ctr))
movieSeats.grid(row=rows,column=columns)
list_of_buttons.append(movieSeats)
ctr += 1
list_of_buttons=[] ## global variable
buttonsMake()
root.mainloop()
我希望它将每个按钮分配给一个名称。我认为全局变量可以做到这一点,但不知道如何 这是别人建议的其他(替代解决方案)。
seats= [["A", "a1", "a2", "a3", "a4", "a5"],
["B", "b1", "b2", "b3", "b4", "b5"],
["C", "c1", "c2", "c3", "c4", "c5"],
["D", "d1", "d2", "d3", "d4", "d5"],
["E", "e1", "e2", "e3", "e4", "e5"]]
def make_buttons():
for r, row in enumerate(seats):
for c, seat in enumerate(row[1:]): # N.B. skip first element
btn = Button(root, text="Empty", bg="#00CC00", height=1,width=6)
btn.name = seat # arbitrary attribute on Button object
btn.grid(row=r,column=c, padx=10, pady=10)
答案 0 :(得分:2)
为按钮分配名称作为全局变量将是棘手的,不值得做。但是你可以做的,一点也不难,就是制作一个你所有按钮的字典,并使字典键成为你想要的“名字”,比如“A1”,每个键的值都会是Button()调用返回的实际对象。
我会在双嵌套for
循环中填充字典。
作为旁注,在双循环中,你可以说,
import string
:
:
names_d = {}
for ....
for ....
buttonName = string.ascii_uppercase[rows] + str(columns + 1) # a working hack
names_d[buttonName] = Button(...
因为我的手上有太多的空闲时间......
def alphanum_name(ai, ni):
return (ai // 26 + 1) * string.ascii_uppercase[ai % 26] + str(ni + 1)
alphanum_name(1,2) - > 'B3'
alphanum_name(26,3) - > 'AA4'