Reputation: 2473
I'm coding a little stocks ticker displayer program with tkinter label and I need to merge in the same line text in red color and green color. How can I do that?
If not, is there any other widget which I can do it with?
Upvotes: 1
Views: 11005
Reputation: 810
If you're looking to get two colours on the same line you can use several labels and use .grid()
to get them on the same line.
If you know you wanted two words and two colours for example you can use something like this:
root = Tk()
Label(root,text="red text",fg="red").grid(column=0,row=0)
Label(root,text="green text",fg="green").grid(column=0,row=1)
mainloop()
Or if you wanted to have a different colours for each word in a string for example:
words = ["word1","word2","word3","word4"]
colours = ["blue","green","red","yellow"]
for index,word in enumerate(words):
Label(window,text = word,fg=colours[index]).grid(column=index,row=0)
Upvotes: 3
Reputation: 385900
You cannot have multiple colors in a label. If you want multiple colors, use a one-line Text widget, or use a canvas with a text item.
Here's a quick and dirty example using a text widget. It doesn't do smooth scrolling, doesn't use any real data, and leaks memory since I never trim the text in the input widget, but it gives the general idea:
import Tkinter as tk
import random
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.ticker = tk.Text(height=1, wrap="none")
self.ticker.pack(side="top", fill="x")
self.ticker.tag_configure("up", foreground="green")
self.ticker.tag_configure("down", foreground="red")
self.ticker.tag_configure("event", foreground="black")
self.data = ["AAPL", "GOOG", "MSFT"]
self.after_idle(self.tick)
def tick(self):
symbol = self.data.pop(0)
self.data.append(symbol)
n = random.randint(-1,1)
tag = {-1: "down", 0: "even", 1: "up"}[n]
self.ticker.configure(state="normal")
self.ticker.insert("end", " %s %s" % (symbol, n), tag)
self.ticker.see("end")
self.ticker.configure(state="disabled")
self.after(1000, self.tick)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
Upvotes: 6