Julio Arriaga
Julio Arriaga

Reputation: 970

My code to change the color of a Label depending on the previous color value is not working

I'm trying to change a color in a label, according to a previous color, but my code wasn't working. So I tried with a dummy and I realized that my if clause is not detecting the value of the foreground as green. It is printing "It is not green", but when I put a print(Et1["foreground"]), it prints "green". Why is that the case?

#Libraries
import tkinter as tk
from tkinter import ttk

#Class to variables
win=tk.Tk()

Et1=ttk.Label(win,text="Text",foreground="green")
Et1.grid(column=0,row=0)

if Et1["foreground"]=="green":
    print("It is green")
else:
    print("It is not green")

#Run loop
win.mainloop()

Upvotes: 0

Views: 39

Answers (1)

Nouman
Nouman

Reputation: 7303

Et1["foreground"] doesn't give you a string. It gives you some tk type object. You will have to convert it to string before, like:

if str(Et1["foreground"])=="green":

Your full code is:

#Libraries
import tkinter as tk
from tkinter import ttk

#Class to variables
win=tk.Tk()

Et1=ttk.Label(win,text="Text",foreground="green")
Et1.grid(column=0,row=0)
if str(Et1["foreground"])=="green":
    print("It is green")
else:
    print("It is not green")

#Run loop
win.mainloop()

Upvotes: 2

Related Questions