Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

tkinter

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()?

enter image description here

# 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

like image 527
Patrick Burns Avatar asked Apr 08 '26 22:04

Patrick Burns


1 Answers

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.

like image 136
Kevin Avatar answered Apr 11 '26 11:04

Kevin