实现图片中的代码
使用Tags标签
注意索引的行是从 1 开始,而列是从 0 开始,,这里的1.7 是指第一行,第八列
background 指的是背景颜色, foreground 指的是字体颜色
from tkinter import *
root = Tk()
#实例化text组件
text = Text(root, width=50, height=5)
#显示出来
text.pack()
text.insert(INSERT,"I love china chengdu")
#1.7 指的是第一行的第八列。
text.tag_add("tag1","1.7","1.12","1.18")
text.tag_config("tag1",background="yellow",foreground="red")
mainloop()
设置多个tag_config会怎么样呢?
例如:
设置多个tag_config 会覆盖原来的旧的,原理和栈一样
将Tages绑定事件
当鼠标进入该文本段的时候,鼠标的样式切换为“hand2”形态,离开文本段的时候切换回“xterm”形态。当鼠标“左键点击操作" 事件的时候,打开一个指定的网站
import webbrowser
from tkinter import *
root = Tk()
# 实例化text组件
text = Text(root, width=50, height=5)
# 显示出来
text.pack()
text.insert(INSERT, "I love China.com")
# 1.7 指的是第一行的第八列。
text.tag_add("link", "1.7", "1.17")
text.tag_config("link", foreground="blue", underline=True)
def show_hand_cursor(event):
text.config(cursor="hand2")
def show_xterm(event):
text.config(cursor="xterm")
def click(event):
webbrowser.open("www.baidu.com")
text.tag_bind("link", "<Enter>", show_hand_cursor)
text.tag_bind("link", "<Leave>", show_xterm)
text.tag_bind("link", "<Button-1>", click)
mainloop()
使用MD5检查内容是否发生改变
from tkinter import *
import hashlib
root = Tk()
# 实例化text组件
text = Text(root, width=50, height=5)
# 显示出来
text.pack()
text.insert(INSERT, "I love China.com")
contents = text.get("1.0", END)
def getSig(contents):
# 将contents变成一个二进制的文件
m = hashlib.md5(contents.encode())
# 返回一个摘要
return m.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()
如何使用MD5进行验证
import hashlib
m = hashlib.md5(contents.encode())
return m.digest()
撤销操作
from tkinter import *
import hashlib
root = Tk()
# 实例化text组件
text = Text(root, width=50, height=5,undo = True)
# 显示出来
text.pack()
text.insert(INSERT, "I love China.com")
def show():
text.edit_undo()
Button(root,text="撤销",command=show).pack()
mainloop()