在自定义tkinter文本框中将单独的行更改为不同的颜色

问题描述 投票:0回答:1

我希望能够根据 CTkTextbox 中的文本内容更改文本的颜色。我已经能够在 tkinter 中找到类似的东西,“https://stackoverflow.com/questions/47591967/changing-the-colour-of-text-automatically-inserted-into-tkinter-widget”,它确实我需要什么,但我无法让它在 customkinter 中工作。我已经尝试过标签,但似乎无论我插入行时指定的标签如何,它都会使用标签配置中定义的最后一个颜色。忽略插入中的 0.0,我实际上希望最后一个插入位于列表的顶部。

有什么想法吗?

import customtkinter

class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()
        self.grid_rowconfigure(0, weight=1)  # configure grid system
        self.grid_columnconfigure(0, weight=1)

        self.textbox = customtkinter.CTkTextbox(master=self, width=400, corner_radius=0)
        self.textbox.grid(row=0, column=0, sticky="nsew")
        self.textbox.configure("1", text_color="red")
        self.textbox.configure("2", text_color="blue")

        self.textbox.insert("0.0", "Text color is red\n", "1")
        self.textbox.insert("0.0", "Text color is blue\n", "2")

app = App()
app.mainloop()

python tkinter textbox tkinter-entry customtkinter
1个回答
0
投票

请注意,

.configure()
用于更改小部件本身的选项,与tag无关。

.tag_config()
应用于 标签相关选项,但应使用 tkinter
Text
小部件的选项,而不是自定义 tkinter 选项:

# use .tag_config() instead of .configure()
# and tkinter option "foreground" is used instead of customtkinter option "text_color"
self.textbox.tag_config("1", foreground="red")
self.textbox.tag_config("2", foreground="blue")
© www.soinside.com 2019 - 2024. All rights reserved.