首页 > 解决方案 > 单个按钮多个事件取决于其他按钮背景 tkinter

问题描述

我有一个按钮 (B),其功能应取决于单击其他按钮。假设我有 3 个可靠的按钮(b1、b2、b3),点击它会改变背景。我对 3 个按钮使用以下命令来更改背景颜色。

B = Button(frame, image=logo, command=data)
b1 = Button(frame, text = "v", command=lambda:b1.config(bg="gray))
b2 = Button(frame, text = "v", command=lambda:b2.config(bg="gray))
b3 = Button(frame, text = "v", command=lambda:b3.config(bg="gray))

因此,当我单击按钮时,背景颜色变为灰色。但是,我想一次只做一个按钮。所以,当我单击一个按钮时,我想将其他按钮更改为前台。通过使用背景颜色,我想编写按钮 B 命令功能。

我尝试如下,但它没有按我的意愿工作:

def data():
    if b1.configure(bg="gray):
       data1()
    if b2.configure(bg="gray):
       data2()
    if b3.configure(bg="gray):
       data3()
    else:
        print('no data')

def data1():
    as per my requirement 
def data2():
    as per my requirement 
def data3():
     as per my requirement 

但是,尽管单击了按钮,但我没有得到任何数据。

很高兴听到一些建议。

标签: pythontkinter

解决方案


要获得您正在寻找的行为,您需要更改command每个按钮的方法。您可以为每个按钮定义单独的处理程序,如下所示:

b1 = Button(frame, text = "v", command=b1_pressed)
b2 = Button(frame, text = "v", command=b2_pressed)
b3 = Button(frame, text = "v", command=b3_pressed)

def b1_pressed():
    b1.config(bg="gray")
    b2.config(bg="red")  # Or any other color.
    b3.config(bg="red")

def b2_pressed():
    b1.config(bg="red")
    b2.config(bg="gray")
    b3.config(bg="red")

def b3_pressed():
    b1.config(bg="red")
    b2.config(bg="red")
    b3.config(bg="gray")

这是很多重复,因此您可以做的是将有关已按下按钮的信息传递给处理程序。

b1 = Button(frame, text = "v", command=lambda: button_pressed(b1))
b2 = Button(frame, text = "v", command=lambda: button_pressed(b2))
b3 = Button(frame, text = "v", command=lambda: button_pressed(b3))

def button_pressed(button):
    for b in [b1, b2, b3]:
        if b is button:
            b.config(bg="gray")
        else:
            b.config(bg="red")

我们需要lambda在其中包装调用,button_pressed以便我们可以传递值(就像您当前在示例中为 config 所做的那样)。目标函数获取此按钮引用并将其与可能按钮列表中的每个成员进行比较。如果匹配,我们将该按钮设置为灰色,如果不匹配,我们将其设置为红色。


推荐阅读