다음 코드를 작성하여 4 개의 버튼을 작성하고 버튼을 클릭 한 후이 버튼의 backround 색상이 변경되고 다른 버튼을 클릭하면이 색상이 변경되고 색상 이전 색상이 기본 색상으로 다시 변경됩니다. 그것은 꽤 잘 작동하지만 코딩은 효율적이지 않습니다. 나는 기본 색상으로 활성화되지 않은 모든 버튼을 설정하기 위해 모든 버튼을 반복하는 루프를 생각하고 있습니다. 이것을 어떻게 할 수 있습니까? @Mitiku에서 목록을 사용하여 솔루션을 제안 같은tkinter에서 버튼 반복하기
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()
은 다음과 같습니다
아래def update_Button(number):
number = number-1
buttons = [Button_1, Button_2, Button_3, Button_4]
buttons[number]["background"] = buttons[number]["activebackground"] = "lightblue"
for button in buttons:
if button == buttons[number]:
pass
else:
button.configure(background="SystemButtonFace")
pass
이것은 완벽하게 작동하며 나는 염두에 두었던 것 이상입니다. 아니요 한 번에 하나의 버튼 만 색칠하고 싶습니다. 고마워요! – Max2603
"한 번에 하나의 단추 만 색칠하고 싶지 않습니다."무엇을 의미합니까? 이것은 한 번에 하나씩 만 색을냅니다. –
삭제 된듯한 코멘트에 소개하고있었습니다. – Max2603