[英]How to set different colors on label text in pandas pie chart
[英]How merge text in a tkinter label with different colors
我正在編寫一個帶有tkinter標簽的小股票股票代碼程序,我需要在紅色和綠色的同一行文本中合並。 我怎樣才能做到這一點?
如果沒有,是否還有其他小部件,我可以用它?
標簽中不能有多種顏色。 如果需要多種顏色,請使用單行文本小部件,或使用帶有文本項的畫布。
這是使用文本小部件的快速而骯臟的示例。 它不做平滑滾動,不使用任何實際數據,並且泄漏內存,因為我從不修剪輸入小部件中的文本,但它給出了一般的想法:
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()
如果你想在同一行上獲得兩種顏色,可以使用幾個標簽並使用.grid()
將它們放在同一行上。
如果你知道你想要兩個單詞和兩個顏色,例如你可以使用這樣的東西:
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()
或者,如果您希望字符串中的每個單詞都有不同的顏色,例如:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.