Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the color of a Tkinter label programmatically?

Tags:

python

tkinter

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

like image 331
Sean W Avatar asked Mar 22 '17 04:03

Sean W


1 Answers

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!

like image 103
abhinav Avatar answered Oct 22 '22 21:10

abhinav