因此,我有一个按钮小部件,我希望它在单击后显示小部件的文本和颜色。我不能使用.cget
方法来执行此操作,因为在循环中创建了多个具有相同名称的按钮,因此它只会给出最后创建的按钮小部件的文本和颜色。尝试不使用复杂的方法并使它尽可能简单。
for x in range(5):
for y in range(10):
if x == 0:
x_row = 'A'
elif x == 1:
x_row = 'B'
elif x == 2:
x_row = 'C'
elif x == 3:
x_row = 'D'
elif x == 4:
x_row = 'E'
seats_button = tkinter.Button(windowmain, text = '%s' % (str(x_row)+str(y+1)), command = lambda: messagebox.showinfo('Testing',seats_button.cget('text')),font=customFont) # Says E10 as it was the last created widget
seats_button.grid(row = x, column = y)
if str(x_row)+str(y+1) in available[0] or str(x_row)+str(y+1) in available[1] or str(x_row)+str(y+1) in available[2] or str(x_row)+str(y+1) in available[3] or str(x_row)+str(y+1) in available[4]:
seats_button["background"] = 'green'
我应该如何解决这个问题?谢谢!
答案 0 :(得分:0)
将lambda
与按钮的command
的字符串参数一起使用,并将字符串参数的默认值设置为按钮文本:
btnText = '%s' % (str(x_row)+str(y+1))
seats_button = tkinter.Button(windowmain, text = btnText, command = lambda s=btnText: messagebox.showinfo('Testing',s),font=customFont)
这是因为定义lambda
时会构造默认值。
根据您的代码更改座位颜色的建议:
使用btn_list
作为键,将array
从本地dictionary
更改为全局btnText
:
btn_list = {} # defined in global area and replaced the line btn_list = [] inside function bookinginterface()
...
btn_list[btnText] = seats_button # replaced the line btn_list.append(seats_button)
定义一个由lambda调用的新函数:
def seat_selected(seatName):
messagebox.showinfo('Testing', seatName)
btn_list[seatName]["background"] = "whatever color you want"
# do other stuff you want
...
...
seats_button = tkinter.Button(windowmain, text=btnText, command=lambda s=btnText: seat_selected(s), font=customFont)