我写了下面的代码来创建4个按钮,在点击一个按钮后,这个按钮的背景颜色正在改变,当我点击另一个按钮时,这个按钮的颜色现在正在改变,而旧按钮的颜色又变回默认颜色。它工作得很好,但编码效率不高。我在想一个循环,它可以将所有不活动的按钮设置为默认颜色。我怎样才能做到这一点?在
from tkinter import *
def update_Button(number):
if number == 1:
Button_1["background"] = Button_1["activebackground"] = "lightblue"
Button_2.configure(background="SystemButtonFace")
Button_3.configure(background="SystemButtonFace")
Button_4.configure(background="SystemButtonFace")
elif number == 2:
Button_2["background"] = Button_2["activebackground"] = "lightblue"
Button_1.configure(background="SystemButtonFace")
Button_3.configure(background="SystemButtonFace")
elif number == 3:
Button_3["background"] = Button_3["activebackground"] = "lightblue"
Button_2.configure(background="SystemButtonFace")
Button_1.configure(background="SystemButtonFace")
Button_4.configure(background="SystemButtonFace")
elif number == 4:
Button_4["background"] = Button_4["activebackground"] = "lightblue"
Button_2.configure(background="SystemButtonFace")
Button_3.configure(background="SystemButtonFace")
Button_1.configure(background="SystemButtonFace")
pass
root = Tk()
Button_font = ("Calibri", 20, "bold")
Button_Size = [70, 70] # width, height
pady = 5
padx = 5
Button_1 = Button(root, text="1", font=Button_font, command=lambda: update_Button(1))
Button_1.grid(sticky="wens", pady=pady, padx=padx)
Button_2 = Button(root, text="2", font=Button_font, command=lambda: update_Button(2))
Button_2.grid(sticky="wens", pady=pady, padx=padx)
Button_3 = Button(root, text="3", font=Button_font, command=lambda: update_Button(3))
Button_3.grid(sticky="wens", pady=pady, padx=padx)
Button_4 = Button(root, text="4", font=Button_font, command=lambda: update_Button(4))
Button_4.grid(sticky="wens", pady=pady, padx=padx)
root.mainloop()
与@Mitiku的建议一样,使用列表的解决方案是:
^{pr2}$
以下是您所需要的:
我们在这里使用的主要有趣的机制是
lambda
。在{{cd2>的值在cd2}时声明。这意味着当我们调用该命令时,我们将传递
Button
小部件在list
中的位置的整数值。在另一方面,使用
^{pr2}$Radiobutton
s可以更容易地实现这一点。请参见以下内容:你可以使用列表。在
相关问题 更多 >
编程相关推荐