如何获取 tkinter Text 对象的内容 [英] How to get the content of a tkinter Text object

查看:150
本文介绍了如何获取 tkinter Text 对象的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 tkinter.TextPython 中创建一个文本区域.有了这个,我想获得他们放入该文本区域的所有输入并将其显示在其上方的输入字段中.它给出了一个错误,说它需要两个参数.

I'm trying to use tkinter.Text to create a text area in Python. With that, I want to get all the input they put into that text area and display it in the Entry field above it. It gives an error saying it needs two arguments.

from Tkinter import *

def create_index():
        var = body.get(0)
        link.insert(10,var)
        file.close()

master = Tk()
Label(master, text="Link:").grid(row=0)
Label(master, text="Body:").grid(row=1)

link = Entry(master)
body = Text(master)

link.grid(row=0, column=1)
body.grid(row=1, column=1)
Button(master, text='Show', command=create_index).grid(row=3, column=1, sticky=W, pady=4)

mainloop()

推荐答案

要从 tkinter.Text 获取所有输入,您应该使用 get 方法从tkinter.Text 用于表示文本区域的对象.在你的情况下,body 应该是 tkinter.Text 类型的变量,所以这里有一个例子:

To get all the input from a tkinter.Text, you should use the method get from the tkinter.Text object you are using to represent the text area. In your case, body should be the variable of type tkinter.Text, so here's an example:

text = body.get("1.0", "end-1c")  

tkinter.Text 对象将它们的内容计算为行和列."1.0" 确切地表明:您希望从第 1 行和字符 0 开始获取内容(这是 tkinter.Text 对象的默认起点).

tkinter.Text objects count their content as rows and columns. The "1.0" indicates exactly that: you want to get the content starting from line 1 and character 0 (this is the default starting point of a tkinter.Text object).

这是一个完整的工作示例,基本上在单击按钮时,会调用方法 get_text 并将 body 的内容添加到 tkinter.我称为 entry 的 Entry 对象(通过使用 tkinter.StringVar 类型的变量.有关详细信息,请参阅文档):

Here's a complete working example, where basically on the click of a button, the method get_text is called and adds the content of body to an tkinter.Entry object that I called entry (through the use of a variable of type tkinter.StringVar. See documentation for more information):

import tkinter

def get_text():
    content = body.get(1.0, "end-1c")
    entry_content.set(content)

master = tkinter.Tk()

body = tkinter.Text(master)
body.pack()

entry_content = tkinter.StringVar()
entry = tkinter.Entry(master, textvariable=entry_content)
entry.pack()

button = tkinter.Button(master, text="Get tkinter.Text content", command=get_text)
button.pack()

master.mainloop()

另一个很好的例子,请参阅其他帖子 和下面的第一条评论.

For another good example, see this other post and the first comment below.

这篇关于如何获取 tkinter Text 对象的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆