how can i get input from Text in tkinter in python 3.8

438 Views Asked by At

I wanted to get input from a tkinter.Text object in python

msg = tkinter.StringVar()
message = tkinter.Entry(mainframe, textvariable=msg)

but it gives an error

I also tried the get method

thetext = message.get('1.0', 'end')

but it gives this error:

return self.tk.call(self._w, 'get', index1, index2)
_tkinter.TclError: invalid command name ".!text"
1

There are 1 best solutions below

0
On

When you close (destroy) window then it removes (destroys) also Entry (and other widgets) and you get error when you try to use Entry. You have to get text from Entry before you close (destroy) window.

OR

Because you use StringVar in Entry so you can get this text from StringVar even after closing (destroying) window.


Minimal working example which shows this problem and solutions.

import tkinter as tk
        
# --- functions ---

def on_click():
    global result

    result = entry.get()

    print('[before] result   :', result)      # OK - before destroying window
    print('[before] StringVar:', msg.get())   # OK - before destroying window
    print('[before] Entry    :', entry.get()) # OK - before destroying window

    root.destroy()

# --- main ---

result = "" # variable for text from `Entry`

root = tk.Tk()

msg = tk.StringVar(root)
entry = tk.Entry(root, textvariable=msg)
entry.pack()

button = tk.Button(root, text='Close', command=on_click)
button.pack()

root.mainloop()

# --- after closing window ---

print('[after] result   :', result)      # OK    - after destroying window
print('[after] StringVar:', msg.get())   # OK    - after destroying window
print('[after] Entry    :', entry.get()) # ERROR - after destroying window