简体   繁体   中英

How can I configure multiple buttons with one function in Tkinter?

def changeColour():
    LT.configure(bg = "white")
    LM.configure(bg = "white")
    LB.configure(bg = "white")

LT = Button(root, width=16, height=8, bg = "blue", command = changeColour)
LT.place(x=10, y=10)

LM = Button(root, width=16, height=8, bg = "red", command = changeColour)
LM.place(x=10, y=150)

LB = Button(root, width=16, height=8, bg = "green", command = changeColour)
LB.place(x=10, y=290)

How do I write the function changeColour() so it changes the colour of the button without a line configuring each button to change colour explicitly?

I'm assuming by "so it changes the colour of the button", you want only the button that was actually clicked to change color.

I know of two approaches.

  1. Use lambdas to supply the name of the clicked widget to the function.

def changeColour(widget):
    widget.config(bg="white")

#...

LM = Button(root, width=16, height=8, bg = "red", command = lambda: changeColour(LM))
LM.place(x=10, y=150)
  1. Use bind instead of command , as the former can deduce what widget raised the event.

def changeColour(event):
    event.widget.config(bg="white")

#...

LT = Button(root, width=16, height=8, bg = "blue")
LT.bind("<1>", changeColour)
LT.place(x=10, y=10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM