如何在tkinter标签中合并具有不同颜色的文本 [英] How merge text in a tkinter label with different colors
问题描述
我正在用tkinter标签编写一个股票行情显示器程序,我需要将同一行文本合并为红色和绿色.我该怎么办?
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?
推荐答案
标签中不能有多种颜色.如果要使用多种颜色,请使用单行文本"小部件,或将画布与文本项一起使用.
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()
这篇关于如何在tkinter标签中合并具有不同颜色的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!