如何将数据从一个 Tkinter Text 小部件复制到另一个?

sou*_*urD 5 python tkinter

from Tkinter import *

root = Tk()
root.title("Whois Tool")

text = Text()
text1 = Text()

text1.config(width=15, height=1)
text1.pack()

def button1():
    text.insert(END, text1)

b = Button(root, text="Enter", width=10, height=2, command=button1)
b.pack()

scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=60, height=15)
text.pack(side=LEFT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

如何将文本小部件中的数据添加到另一个文本小部件?

例如,我试图将数据插入text1text,但它不起作用。

Mat*_*hen 5

您试图Text在另一个Text小部件的末尾插入一个引用(没有多大意义),但您真正想要做的是将一个Text小部件的内容复制到另一个小部件:

def button1():
    text.insert(INSERT, text1.get("1.0", "end-1c"))
Run Code Online (Sandbox Code Playgroud)

在我看来,这不是一种直观的方法。"1.0"表示行1,列0。是的,行是 1-indexed,列是 0-indexed。


请注意,您可能不想Tkinter使用from Tkinter import *. 它可能会导致混乱。我建议使用:

import Tkinter
text = Tkinter.Text()
Run Code Online (Sandbox Code Playgroud)

另一种选择是:

import Tkinter as tk
text = tk.Text()
Run Code Online (Sandbox Code Playgroud)

您可以选择一个短名称(如"tk")。无论如何,您应该坚持使用一种库的导入机制。