【问题标题】:How to make button widget display text and colour once pressed如何使按钮小部件在按下后显示文本和颜色
【发布时间】:2019-04-23 10:52:04
【问题描述】:

所以我有一个按钮小部件,我希望它在单击后显示小部件的文本和颜色。我不能使用.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

【问题讨论】:

    标签: python button tkinter widget


    【解决方案1】:

    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)
    

    【讨论】:

    • 座椅颜色怎么样?
    猜你喜欢
    • 2021-07-07
    • 2020-11-07
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 2020-12-17
    相关资源
    最近更新 更多