gpt4 book ai didi

python - 单个按钮多个事件取决于其他按钮背景 tkinter

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:36 25 4
gpt4 key购买 nike

我有一个按钮 (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

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

很高兴听到一些建议。

最佳答案

要获得您正在寻找的行为,您需要更改每个按钮的 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 所做的那样)。目标函数获取此按钮引用并将其与可能按钮列表中的每个成员进行比较。如果匹配,我们将该按钮设置为灰色,如果不匹配,我们将其设置为红色。

关于python - 单个按钮多个事件取决于其他按钮背景 tkinter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54764553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com