如何使按钮小部件在按下后显示文本和颜色

2024-04-26 00:19:22 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我有一个按钮小部件,我希望它显示的文本和颜色的小部件一旦点击。我不能使用.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'

我该如何着手解决这个问题?谢谢

完整代码:https://pastebin.com/awQ50bp3


Tags: or方法in文本for颜色部件button
1条回答
网友
1楼 · 发布于 2024-04-26 00:19:22

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时构造的

根据您的代码更改座椅颜色的建议:

使用btnText作为键,将btn_list从本地array更改为全局dictionary

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)

相关问题 更多 >