How merge text in a tkinter label with different colors

£可爱£侵袭症+ 提交于 2021-01-28 14:13:25

问题


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?


回答1:


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()



回答2:


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)


来源:https://stackoverflow.com/questions/24760910/how-merge-text-in-a-tkinter-label-with-different-colors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!