Tags标签用于设置Text组件中内容的字体等属性。
Tag:SEL 表示对应的选中内容。
可以自定义任意的tags数量,名称可以任意。
tag_add():为指定的文本添加Tags
tag_config():可以设置Tags的样式
from tkinter import *
root = Tk()
text = Text(root,width = 30,height =5)
text.pack()
text.insert(INSERT,'I love Python!')
text.tag_add('tag1','1.2','1.7','1.7')
text.tag_config('tag1',background = 'yellow',foreground = 'red')
mainloop()
另外,还允许这些文本、组件、图片等与键盘鼠标事件相关联。
from tkinter import *
import webbrowser
root = Tk()
text = Text(root,width = 30,height = 5)
text.pack()
text.insert(INSERT,'I love Fishc.com')
text.tag_add('link',1.7,1.16)
text.tag_config('link',foreground = 'blue',underline = True)
def show_hand_cursor(event):
text.config(cursor = 'arrow')
def show_arrow_cursor(event):
text.config(cursor = 'xterm')
def click(event):
webbrowser.open('http://www.fishc.com')
text.tag_bind('link','<Enter>',show_hand_cursor)
text.tag_bind('link','<Leave>',show_arrow_cursor)
text.tag_bind('link','<Button-1>',click)
mainloop()
Text组件使用技巧:
第一种,判断内容是否发生变化。通过判断Text组件中文本的MD5摘要来判断是否发生变化。
from tkinter import *
import hashlib #md5获取模块
root = Tk()
text = Text(root,width = 30,height = 5)
text.pack()
text.insert(INSERT,'I love Fishc.com')
contents = text.get(1.0,END)
def getSig(contents):
m = hashlib.md5(contents.encode()) #hashlib.md5(data)函数中,data参数的类型应该是bytes。
#也就是说我们在进行hash前必须把数据转换成bytes类型,用encode进行转码。
return m.digest() #digest()方法是获取摘要
Sig = getSig(contents)
def check():
contents = text.get(1.0,END)
if Sig != getSig(contents):
print('请保存')
else:
print('安全')
Button(root,text = '检查',command = check).pack()
mainloop()
第二种,使用search()方法进行查找操作。
需要点知识储备:
index()方法用于将所支持的‘索引’格式转换为‘行.列’格式的索引号:
print(text.index(INSERT))
text.insert(INSERT, “You are good!”)
print(text.index(INSERT))
如果你需要跟踪一个位置,那么你可以将该位置‘标记‘下来(请参考下方Mark用法)
text.insert(INSERT, “You are good!”)
text.mark_set(“here”, ‘1.8’)
text.insert(“here”, “very “)
最后,使用 search() 方法可以搜索 Text 组件中的内容。你可以提供一个确切的目标进行搜索(默认),也可以使用 Tcl 格式的正则表达式进行搜索(需设置 regexp 选项为 True)
from tkinter import *
root = Tk()
text = Text(root, width=30, height=5)
text.pack()
text.insert(INSERT, "I love FishC.com!")
# 将任何格式的索引号统一为元祖 (行,列) 的格式输出
def getIndex(text, index):
return tuple(map(int, str.split(text.index(index), ".")))
'''这句困扰我一大会,哎,基础没打好!~
分解来理解:split()以拆分字符串得到list,
然后map()把list的每一项str转换为int,
tuple()把list转换为tuple。
改为这样就好理解了:
b = text.index(index)
a = b.split('.')
return tuple(map(int, a))
'''
start = 1.0
while True:
pos = text.search("o", start, stopindex=END)
if not pos:
break
print("找到啦,位置是:", getIndex(text, pos))
start = pos + "+1c" # 将 start 指向下一个字符
mainloop()