Python Forum

Full Version: Restoring Tkinter widget background to original color
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to restore the widget background back to it's original color if the button is clicked again for the 5 buttons listed below as btn1,btn2,btn3,btn4,btn5. The first time the buttons are clicked
the background color changes to red as you can see with the def on_click function. I want the buttons to change back to the original color if they are clicked again. So basically I want the background color to change to red when the buttons are clicked and back to original color if the buttons are already red. How would I do this?
from tkinter import *
from PIL import ImageTk, Image
import random

root = Tk()
frame = Frame(root)
root.title('Learn to Code at')

def on_click(event):

def open():
    global my_img
    global image2
    global image3
    global image4
    global image5
    global image6
    top = Toplevel()
    top.title('First Roll')
    lbl = Label(top, text="Your first roll is:").pack()
    lbl2 = Label(top, text="Click on the dice you would like to keep for this round.").pack()
    my_img = ImageTk.PhotoImage("C:\\Users\\Dan\\Desktop\\Alea_1.png"))
    image2 = ImageTk.PhotoImage("C:\\Users\\Dan\\Desktop\\Alea_2.png"))
    image3 = ImageTk.PhotoImage("C:\\Users\\Dan\\Desktop\\Alea_3.png"))
    image4 = ImageTk.PhotoImage("C:\\Users\\Dan\\Desktop\\Alea_4.png"))
    image5 = ImageTk.PhotoImage("C:\\Users\\Dan\\Desktop\\Alea_5.png"))
    image6 = ImageTk.PhotoImage("C:\\Users\\Dan\\Desktop\\Alea_6.png"))

    dice = [my_img, image2, image3, image4, image5, image6]

    rdice = random.choice(dice)
    rdice2 = random.choice(dice)
    rdice3 = random.choice(dice)
    rdice4 = random.choice(dice)
    rdice5 = random.choice(dice)

    btn1 = Button(top, image=rdice)
    btn1.bind('<Button-1>', on_click)
    btn2 = Button(top, image=rdice2)
    btn2.bind('<Button-1>', on_click)
    btn3 = Button(top,image=rdice3)
    btn3.bind('<Button-1>', on_click)
    btn4 = Button(top,image=rdice4)
    btn4.bind('<Button-1>', on_click)
    btn5 = Button(top,image=rdice5)
    btn5.bind('<Button-1>', on_click)

btn = Button(frame, text="Open Second Window",command = open).pack()

You first have to tell the function, on_click, which button was clicked. Then you can use the config option to get the current background color and change it accordingly.