简体   繁体   中英

Python Tkinter - Get value from Entry after root.destroy()

I create entry field and after press <Enter> or submit button i call root.destroy() , but how i can get value from Entry after destroy?

When i call root.close() i can get value from Entry if i call self.EntryName.get() , but how i can do it with root.destroy() ?

在此处输入图片说明

# Python 3.4.1

import io
import requests
import tkinter as tk
from PIL import Image, ImageTk

def get_image():
    im = requests.get('http://lorempixel.com/' + str(random.randint(300, 400)) + '/' + str(random.randint(70, 120)) + '/')
    return Image.open(io.BytesIO(im.content))


class ImageSelect(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)

        master.resizable(width=False, height=False)
        master.title('Image manager')
        master.iconify = False
        master.deiconify = False
        master.grab_set = True

        image = ImageTk.PhotoImage(get_image())
        self.image = tk.Label(image=image)
        self.image.image = image
        self.image.grid(row=0, columnspan=3)


        self.reload = tk.Button(text='Reload').grid(row=1, column=0, sticky='w')
        self.path = tk.Entry().grid(row=1, column=1, sticky='we')
        self.submit = tk.Button(text='Submit', command=self.close).grid(row=1, column=2, sticky='e')

    def close(self):
        self.master.destroy()

if __name__ == '__main__':
    root = tk.Tk()
    app = ImageSelect(master=root)
    app.mainloop()

    # This code i want execute after windows destroyed. 
    # This line return this error
    # _tkinter.TclError: invalid command name ".57818448"
    # print(app.path.get()) # <---- Error

Thanks

Create a StringVariable , which will retain the value of the entry, even after the window is destroyed.

#inside __init__ 
self.pathVar = tk.StringVar()
self.path = tk.Entry(textvariable=self.pathVar)
self.path.grid(row=1, column=1, sticky='we')

#...

if __name__ == '__main__':
    root = tk.Tk()
    app = ImageSelect(master=root)
    app.mainloop()
    print(app.pathVar.get())

By the way, don't do self.path = tk.Entry().grid() . This assigns the result of grid , None, to self.path . If you want self.path to point to the Entry, you need to grid it on a separate line like I did above.

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