【问题标题】:Adding coloured text to selected text - Tkinter将彩色文本添加到选定文本 - Tkinter
【发布时间】:2015-07-31 12:29:27
【问题描述】:

我目前正在尝试编写一个程序,在 Tkinter 中将彩色文本添加到所选文本的两侧。

到目前为止,我所做的是在所选文本的两侧添加文本,这是我使用的功能:

def addTerm(self):
    self.txt.insert(tk.SEL_FIRST,'\\term{')
    self.txt.insert(tk.SEL_LAST,'}' )

所以如果我有一个 WORD 并且我选择了它,在调用这个函数之后它就变成了 \术语{字}。我想知道是否有办法改变我正在添加的文本的颜色,这样当我对所选文本使用该函数时,它会添加'\term{'和'}',例如红色,但是它不会改变它们之间文本的颜色。

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    为周围的文本添加标签:

    tk.SEL_FIRST + '-6c', tk.SEL_FIRST  # for \term{
    tk.SEL_LAST, tk.SEL_LAST + '+1c'    # for }
    

    使用Text.tag_config(tag_name, background=...)设置颜色


    在下面的例子中,我使用term作为标签名:

    try:
        import Tkinter as tk
    except ImportError:
        import tkinter as tk
    
    
    class MyFrame(tk.Frame):
    
        def __init__(self, master):
            tk.Frame.__init__(self, master)
            self.txt = tk.Text(self)
            self.txt.pack()
            self.txt.insert(0.0, 'hello\nworld')
            self.btn = tk.Button(self, text='add_term', command=self.add_term)
            self.btn.pack()
            self.txt.tag_config('term', background='red')
    
        def add_term(self):
            self.txt.insert(tk.SEL_FIRST,'\\term{')
            self.txt.insert(tk.SEL_LAST,'}' )
            self.txt.tag_add('term', tk.SEL_FIRST + '-6c', tk.SEL_FIRST)
            self.txt.tag_add('term', tk.SEL_LAST, tk.SEL_LAST + '+1c')
    
    root = tk.Tk()
    f = MyFrame(root)
    f.pack()
    root.mainloop()
    

    更新

    调用insert时可以指定标签名,而不是事后添加标签:

    def add_term(self):
        self.txt.insert(tk.SEL_FIRST, '\\term{', 'term')
        self.txt.insert(tk.SEL_LAST, '}', 'term')
    

    【讨论】:

    • @BryanOakley,感谢您提供的信息。我相应地更新了答案。真的很高兴知道它。
    【解决方案2】:

    当你插入文本时,你可以给它一个标签的名字,或者在插入文本时应用到文本的标签:

    def addTerm(self):
        self.txt.insert(tk.SEL_FIRST,'\\term{',("markup",))
        self.txt.insert(tk.SEL_LAST,'}', ("markup",))
    

    然后您需要将标签配置为具有所需的属性。您可以在首次创建文本小部件时执行此操作:

    self.txt.tag_configure("markup", foreground="gray")
    

    【讨论】:

      【解决方案3】:

      这里有点回答:How to change the color of certain words in the tkinter text widget?

      你需要在init函数中添加一个tag

      self.txt.tag_configure("COLOR", foreground="red")
      

      你可以这样着色:

      self.text.tag_add("COLOR", 1.0 , "sel.first")  
      self.text.tag_add("COLOR", "sel.last", "end")  
      

      例如,使用链接帖子中提供的代码:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-19
        • 2023-03-11
        • 2011-07-27
        • 1970-01-01
        • 2012-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多