我有一个按钮(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))
Run Code Online (Sandbox Code Playgroud)
因此,当我单击按钮时,背景颜色变为灰色.但是,我想一次只做一个按钮.因此,当我单击一个按钮时,我想将其他按钮更改为前景.通过使用背景颜色,我想编写按钮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
Run Code Online (Sandbox Code Playgroud)
但是,尽管点击按钮,我仍然没有数据.
很高兴听到一些建议.
要获得您正在寻找的行为,您需要更改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")
Run Code Online (Sandbox Code Playgroud)
这是很多重复,所以你可以做的是传递有关按下按钮的信息.
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")
Run Code Online (Sandbox Code Playgroud)
我们需要lambda在那里包装调用,button_pressed以便我们可以传递值(就像你目前在你的例子中为config做的那样).目标函数接受此按钮引用,并将其与可能按钮列表中的每个成员进行比较.如果它匹配,我们将该按钮设置为灰色,如果不匹配,我们将其设置为红色.
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |