Python Tkinter - 在 root.destroy() 之后从 Entry 中获取值 [英] Python Tkinter - Get value from Entry after root.destroy()

查看:70
本文介绍了Python Tkinter - 在 root.destroy() 之后从 Entry 中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

谢谢

推荐答案

创建一个 StringVariable,它会保留条目的值,即使在窗口被销毁后也是如此.

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

<小时>

顺便说一下,不要做self.path = tk.Entry().grid().这将 grid 的结果,None,分配给 self.path.如果你想让 self.path 指向 Entry,你需要像我上面所做的那样将它 grid 放在一个单独的行上.


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.

这篇关于Python Tkinter - 在 root.destroy() 之后从 Entry 中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆