如何通过进入同一个小部件来将文本输入到两个文本小部件中

Kum*_*tam 3 tkinter python-3.x tkinter-text

我想要一种方法,通过将文本输入到单个文本小部件中,可以将文本插入到两个小部件中。简单来说,在编程中,我想将文本小部件的所有功能和事件绑定到另一个文本小部件。我试过了

txt=Text(root,height=300,width=300)
txt.pack()
text=Text(root,height=300,width=300)
text.pack()
def func(event):
    text.delete("1.0","end")
    text.insert(INSERT,txt.get("1.0","end"))
txt.bind(func,<Any-KeyPress>)
Run Code Online (Sandbox Code Playgroud)

但这不是一个好的选择,因为它需要时间并且显示出一些延迟,并且当文本变长时会出现较长的延迟。

Bry*_*ley 5

如果您希望两个文本小部件的内容相同,则文本小部件有一个很少使用的功能,称为对等小部件。实际上,您可以拥有多个共享相同底层数据结构的文本小部件。

规范的 tcl/tk 文档是这样描述同级的:

文本小部件单独存储有关每行文本内容、标记、标签、图像和窗口以及撤消堆栈的所有数据。

虽然无法直接访问此数据存储(即没有文本小部件作为中介),但可以创建多个文本小部件,每个文本小部件都呈现相同基础数据的不同视图。此类文本小部件称为对等文本小部件。

不幸的是,tkinter 对文本小部件对等的支持并不完整。但是,可以创建一个使用对等功能的新小部件类。

The following defines a new widget, TextPeer. It takes another text widget as its master and creates a peer:

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})
Run Code Online (Sandbox Code Playgroud)

You use this similar to how you use a Text widget. You can configure the peer just like a regular text widget, but the data will be shared (ie: you can have different sizes, colors, etc for each peer)

Here's an example that creates three peers. Notice how typing in any one of the widgets will update the others immediately. Although these widgets share the same data, each can have their own cursor location and selected 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()
Run Code Online (Sandbox Code Playgroud)