python - 单个按钮多个事件取决于其他按钮背景 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
但是,尽管单击了按钮,但我没有得到任何数据。
很高兴听到一些建议。
解决方案
要获得您正在寻找的行为,您需要更改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 所做的那样)。目标函数获取此按钮引用并将其与可能按钮列表中的每个成员进行比较。如果匹配,我们将该按钮设置为灰色,如果不匹配,我们将其设置为红色。
推荐阅读
- angular - 如何从订阅中返回价值?
- swift - 为什么这个闭包被调用了 1201 次而不是 900 次?
- c# - 无法在 Unity 中序列化和反序列化 JSON
- c# - 如何下载 Angular 6 中的 excel 文件
- r - 使用 splitTools 将折叠列附加到训练数据框
- python - 如何解决 AttributeError:“系列”对象没有属性“_mgr”
- vue.js - Nuxt.js 生成和 Three.js - SyntaxError: 不能在模块外使用 import 语句
- sql - 如何返回满足特定条件的行列表以及它之前的行?
- windows - 获取 git 中最后两个标签之间的提交列表 - 在 Windows 上 - 不知道标签
- javascript - 使JS生成的文档可以保存到磁盘