如果您希望两个文本小部件的内容相同,则文本小部件有一个很少使用的功能,称为对等小部件。实际上,您可以拥有多个共享相同底层数据结构的文本小部件。
The 规范的 tcl/tk 文档同行是这样描述的:
文本小部件单独存储有关每行文本内容、标记、标签、图像和窗口以及撤消堆栈的所有数据。
虽然无法直接访问此数据存储(即没有文本小部件作为中介),但可以创建多个文本小部件,每个文本小部件都针对相同的基础数据呈现不同的视图。此类文本小部件称为对等文本小部件。
不幸的是,tkinter 对文本小部件对等的支持并不完整。但是,可以创建一个使用对等功能的新小部件类。
下面定义了一个新的小部件,TextPeer
。它以另一个文本小部件作为其主控并创建一个对等体:
import tkinter as tk
class TextPeer(tk.Text):
"""A peer of an existing text widget"""
count = 0
def __init__(self, master, cnf={}, **kw):
TextPeer.count += 1
parent = master.master
peerName = "peer-{}".format(TextPeer.count)
if str(parent) == ".":
peerPath = ".{}".format(peerName)
else:
peerPath = "{}.{}".format(parent, peerName)
# Create the peer
master.tk.call(master, 'peer', 'create', peerPath, *self._options(cnf, kw))
# Create the tkinter widget based on the peer
# We can't call tk.Text.__init__ because it will try to
# create a new text widget. Instead, we want to use
# the peer widget that has already been created.
tk.BaseWidget._setup(self, parent, {'name': peerName})
您使用它的方式类似于使用Text
小部件。您可以像常规文本小部件一样配置对等点,但数据将共享(即:每个对等点可以有不同的大小、颜色等)
这是创建三个对等点的示例。请注意,输入任何一个小部件将如何立即更新其他小部件。尽管这些小部件共享相同的数据,但每个小部件都可以有自己的光标位置和选定的文本。
import tkinter as tk
root = tk.Tk()
text1 = tk.Text(root, width=40, height=4, font=("Helvetica", 20))
text2 = TextPeer(text1, width=40, height=4, background="pink", font=("Helvetica", 16))
text3 = TextPeer(text1, width=40, height=8, background="yellow", font=("Fixed", 12))
text1.pack(side="top", fill="both", expand=True)
text2.pack(side="top", fill="both", expand=True)
text3.pack(side="top", fill="both", expand=True)
text2.insert("end", (
"Type in one, and the change will "
"appear in the other."
))
root.mainloop()