Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

python - How to get the content of a tkinter Text object

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...