0

I'm new to tkinter and I'm trying to change the color and background of a specific word in a label when I press "Return". The code works, but it changes the color of the entire label, and I don't know how I can specify it so it only changes the color of the first word on the label (w_1). This is the code I have:

,Thank you!

from tkinter import *
import random

root = Tk()

list_1 = ["about","above","add","after","again","air","all","almost","along","also","always","America","an"]
w_1 = random.choice(list_1)
w_2 = random.choice(list_1)
w_3 = random.choice(list_1)
w_4 = random.choice(list_1)
w_5 = random.choice(list_1)

def color(event):
   list_label.config(fg="#808080")

list_label = Label(root, text=w_1 + " " + w_2 + " " + w_3 + " " + w_4 + " " + w_5, width=30)
list_label.grid(row=1, column=0, pady=5, padx=150)

root.bind("<Return>", color)

root.mainloop()


  • Maybe the simplest solution is to use two labels, one for w_1 and one for the other words. – j_4321 Sep 17 '20 at 09:02
  • `Label` can have only one color. You may put every word in separated `Label` or you can use widget `Text` which can use `tags` to assign colors. – furas Sep 17 '20 at 11:42
  • BTW: instead of `w_1`, `w_2`, etc. you could keep it in list - ie. `words` - and then you could create string with `text = " ".join(words)`. You could also use `for`-loop to create many Labels with different colors. – furas Sep 17 '20 at 11:44
  • BTW: `random` has also function `choices()` with char `s` at the end - and you can select five items at once `words = random.choices(list_1, k=5)` – furas Sep 17 '20 at 11:46

0 Answers0