2013-02-09 70 views

回答

13

主要思路是運用標籤到您要自定義文本的部分。您可以使用方法tag_configure創建具有特定樣式的標籤,然後您只需要使用方法tag_add將此標籤應用於要更改的文本部分。 您也可以使用方法tag_remove刪除標籤。

以下是使用tag_configure,tag_addtag_remove方法的示例。

#!/usr/bin/env python3 

import tkinter as tk 
from tkinter.font import Font 

class Pad(tk.Frame): 

    def __init__(self, parent, *args, **kwargs): 
     tk.Frame.__init__(self, parent, *args, **kwargs) 

     self.toolbar = tk.Frame(self, bg="#eee") 
     self.toolbar.pack(side="top", fill="x") 

     self.bold_btn = tk.Button(self.toolbar, text="Bold", command=self.make_bold) 
     self.bold_btn.pack(side="left") 

     self.clear_btn = tk.Button(self.toolbar, text="Clear", command=self.clear) 
     self.clear_btn.pack(side="left") 

     # Creates a bold font 
     self.bold_font = Font(family="Helvetica", size=14, weight="bold") 

     self.text = tk.Text(self) 
     self.text.insert("end", "Select part of text and then click 'Bold'...") 
     self.text.focus() 
     self.text.pack(fill="both", expand=True) 

     # configuring a tag called BOLD 
     self.text.tag_configure("BOLD", font=self.bold_font) 

    def make_bold(self): 
     # tk.TclError exception is raised if not text is selected 
     try: 
      self.text.tag_add("BOLD", "sel.first", "sel.last")   
     except tk.TclError: 
      pass 

    def clear(self): 
     self.text.tag_remove("BOLD", "1.0", 'end') 


def demo(): 
    root = tk.Tk() 
    Pad(root).pack(expand=1, fill="both") 
    root.mainloop() 


if __name__ == "__main__": 
    demo() 

如果你不知道什麼sel.firstsel.last是,檢查出this postthis參考。

+0

如果我需要做與畫布文本項目相同的東西? – Kay 2017-10-24 05:48:28

4

有一個看看這個例子:

from tkinter import * 

root = Tk() 

text = Text(root) 
text.insert(INSERT, "Hello, world!\n") 
text.insert(END, "This is a phrase.\n") 
text.insert(END, "Bye bye...") 
text.pack(expand=1, fill=BOTH) 

# adding a tag to a part of text specifying the indices 
text.tag_add("start", "1.8", "1.13") 
text.tag_config("start", background="black", foreground="yellow") 

root.mainloop() 
+2

tag_add(tagname,startindex [,endindex] ...) 該方法標記由startindex定義的位置或由位置startindex和endindex定界的範圍。 – 2013-02-09 09:21:49

+0

事情是與1.8和1.13是文本是我想要它改變顏色時,文本出現 – Elxafil 2013-06-08 06:54:17

4

我已經做了聊天客戶端。 我使用自定義的相當容易使用的Text小部件突出顯示對話的某些部分,它允許您使用正則表達式應用標籤。它基於以下帖子:How to highlight text in a tkinter Text widget

在這裏你有使用的例子:

# "text" is a Tkinter Text 

# configuring a tag with a certain style (font color) 
text.tag_configure("red", foreground="red") 

# apply the tag "red" 
text.highlight_pattern("word", "red") 
相關問題