0

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"
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • 1
    Please provide a complete [mcve]. The error you show ("invalid command...") happens if you try to use a widget after it has been destroyed. – Bryan Oakley Jun 27 '20 at 12:10
  • you may have to copy text from Entry to other variable before you close/destroy window. But you should still have this text in `StringVar` - `msg.get()` – furas Jun 27 '20 at 12:13

1 Answers1

0

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
furas
  • 134,197
  • 12
  • 106
  • 148