Tushar Gautam
Tushar Gautam

Reputation: 295

How to fetch the text from scrolled text widget?

I need to fetch what is entered in tkinter.scrolledtext.ScrolledText which is a Textbox. However, ScrolledText definition doesn't accept textvariable argument. So How can I do it?

Upvotes: 1

Views: 3617

Answers (2)

Preet Govind
Preet Govind

Reputation: 71

It worked for me , when using scrollbar Wrote a method for getting the value from the scrolledtext and then updated this value for the label. this method named for_display was written as a command in button argument.

    import tkinter as tk
    import tkinter.scrolledtext as scrolledtext
    
    def for_dsplyBtn():
        str=txt.get("1.0",'end')
        display["text"]=str
    
    
    window=tk.Tk()
    intro=tk.Label(text="intro")
    intro.pack()
    txt = scrolledtext.ScrolledText(window, undo=True)
    txt['font'] = ('consolas', '12')
    txt.pack(expand=True, fill='both')
    display=tk.Label(window)
    display.pack()
    btn=tk.Button(window,text="Display", command= lambda : for_dsplyBtn())
    btn.pack()
    tk.mainloop()

Upvotes: 0

Nae
Nae

Reputation: 15335

textvariable is not a must for widgets to have their text strings manipulated. Below example gets the content of the text and then puts it in lbl's text:

import tkinter as tk
import tkinter.scrolledtext as tkst

def put_text_in_lbl():
    global text, lbl
    fetched_content = text.get('1.0', 'end-1c')
    lbl['text'] = "What's written in text: " + fetched_content

root = tk.Tk()

text = tkst.ScrolledText(root)
lbl = tk.Label(root)
btn = tk.Button(root, text="Display", command=put_text_in_lbl)

# display
text.pack()
lbl.pack()
btn.pack()

root.mainloop()

Upvotes: 2

Related Questions