简体   繁体   中英

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

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM