Home > Enterprise >  Rgb color effect in a label text, tkinter python
Rgb color effect in a label text, tkinter python

Time:09-29

Hi I was just experimenting with some code, I am trying to change the color of text inside a label(like the rgb color effect in physical keyboards), with the following code I did get the color to change, but what I am trying to achieve is getting the colors of each letter of the text to change, but I have no idea how to do that.

below is the code I have written :

import tkinter as tk
import time
import random

color_list = ["red","blue","green","cyan1","yellow","purple"]



root = tk.Tk()
root.geometry("800x600")


i=0

txt = "Hello world"

l1 = tk.Label(root, text=txt)
l1.pack(pady=10)



def text():
   #global i 
   global l1
   global root
   global color_list
   global txt
   try:
      while True:
        #for j in range(0,len(txt)):
        random_value = random.randint(0,5)
        l1.config(fg=f"{color_list[random_value]}")
        l1.update()
        time.sleep(1)

    '''if i == 100:
        l1.config(text="Process completed")
        time.sleep(5)
        root.destroy()'''
      print()

except:
    print("Program Exited")

root.after(3000, lambda: text())
root.mainloop() 

CodePudding user response:

As mentioned in comments, using Text is one approach, but I feel using a Frame, is a more similar approach to what you have done. The basic idea is to create a main frame which will be like the entire sentence/word, then create each letter as individual labels, and change its color. You should not use while because it will interfere with the mainloop causing the application to freeze.

import tkinter as tk
import random

root = tk.Tk()
color_list = ["red","blue","green","cyan1","yellow","purple"]
text = 'Hello World'

def change():
     for wid in alpha.winfo_children(): # Each letter 
          rand = random.randint(0,len(color_list)-1) # Get a random color
          wid.configure(fg=color_list[rand]) # Change the letter to that random color
     
     root.after(50,change) # Repeat every 50 millisecond

alpha = tk.Frame(root)
alpha.pack()

count = 0
for idx,letter in enumerate(text):
     tk.Label(alpha,text=letter,fg=color_list[count],font=(0,21)).grid(row=0,column=idx)
     if count < len(color_list)-1: 
          count  = 1
     else:
          count = 0

change()
root.mainloop()

Most of the code is pretty self-explanatory.

  • Related