Home > Back-end >  Conditional function based on label foreground color
Conditional function based on label foreground color

Time:01-31

I'm trying to get output based on foreground color of a label.

This is the code:

from tkinter import Tk
from tkinter.ttk import Label, Style

root = Tk()
root.geometry("200x200")

class TestMe:
    def __init__(self):
        score_labels = {}
        score_names = ["score1", "score2", "score3"]

        s=Style()
        s.configure('score.TLabel', borderwidth=5, relief="solid",
                    font=('Helvetica', '12', 'bold'))
        for name in score_names:
            # Initialize score_name labels
            Label(root, text=name, style='score.TLabel', width=10,
                 ).grid(row=score_names.index(name), column=0)
            # Initialize score lables
            score_label = Label(root, text="", style='score.TLabel', width=3,
                                anchor='center')
            score_label.grid(row=score_names.index(name), column=1)            
            score_label.bind('<Button-1>', self.on_left_click)
            score_label.bind('<Button-3>', self.on_right_click)
            # Add score label to score_labels dictionary by score_name
            score_labels[name] = score_label
        # Set text and foreground color
        score_labels["score1"].config(text="0", foreground='red')
        score_labels["score2"].config(text="1", foreground='black')

    def on_left_click(self, event):
        if event.widget["text"]:
            print(event.widget["foreground"])

    def on_right_click(self, event):
        if event.widget["foreground"] == 'red':
            print(event.widget["foreground"])
        else:
            print("foo")          

TestMe()
root.mainloop()

Now, when i first right click on the 'score1' score label (the "0") i expect 'red' but i get 'foo'.

But when i first left click (and get 'red' as expected) and then right-click THEN i get 'red' from the right click.

Why do i need to left click first in order to make right click give me the correct value?

How to make right click output 'red' on the first try?

CodePudding user response:

This is because what the widget stores as the red value is not a typical string but a tkinter object.

First, convert the value returned by event.widget["foreground"] to a string. So, Replace

if event.widget["foreground"] == 'red':

With

if str(event.widget["foreground"]) == 'red':
  •  Tags:  
  • Related