Python Tkinter - 在root.destroy()之后从Entry获取值

时间:2014-07-25 15:30:01

标签: python tkinter

我创建输入字段并在按下<Enter>或提交按钮后调用root.destroy(),但是如何在销毁后从Entry获取值?

当我致电root.close()时,如果我致电self.EntryName.get(),我可以从Entry中获取价值,但我如何使用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

由于

1 个答案:

答案 0 :(得分:6)

创建一个StringVariable,即使在窗口被销毁之后也会保留条目的值。

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

顺便说一句,不要做self.path = tk.Entry().grid()。这会将grid,None的结果分配给self.path。如果您希望self.path指向条目,则需要像我上面那样在单独的行上grid