Search code examples
pythontkinter

How to change the color of a Tkinter label programmatically?


I am trying to change the color of a Tkinter label when ever the user clicks the check button. I am having trouble writing the function correctly and connecting that to the command parameter.

Here is my code:

import Tkinter as tk

root = tk.Tk()
app = tk.Frame(root)
app.pack()

label = tk.Label(app, bg="white", pady=5, font=(None, 1), height=20, width=720)
checkbox = tk.Checkbutton(app, bg="white", command=DarkenLabel)
label.grid(row=0, column=0, sticky="ew")
checkbox.grid(row=0, column=0, sticky="w")

def DarkenLabel():
    label.config(bg="gray")

root.mainloop()

Thank you


Solution

  • In your code, command=DarkenLabel is unable to find reference to the function DarkenLabel. Thus you need to define the function above that line, so you may use your code as following:

    import Tkinter as tk
    
    
    def DarkenLabel():
        label.config(bg="gray")
    
    root = tk.Tk()
    app = tk.Frame(root)
    app.pack()
    
    label = tk.Label(app, bg="white", pady=5, font=(None, 1), height=20, width=720)
    checkbox = tk.Checkbutton(app, bg="white", command=DarkenLabel)
    label.grid(row=0, column=0, sticky="ew")
    checkbox.grid(row=0, column=0, sticky="w")
    root.mainloop()
    

    Hope it helps!