Tkinter从弹出窗口读取输入值

时间:2019-01-04 08:25:13

标签: python tkinter popup

创建一个弹出窗口,要求输入电子邮件,然后在按“确定”时打印电子邮件,这是我的代码:

import tkinter as tk

class PopUp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        tk.Label(self, text="Main Window").pack()
        popup = tk.Toplevel(self)
        popup.wm_title("EMAIL")
        popup.tkraise(self)
        tk.Label(popup, text="Please Enter Email Address").pack(side="left", fill="x", pady=10, padx=10)
        self.entry = tk.Entry(popup, bd=5, width=35).pack(side="left", fill="x")
        self.button = tk.Button(popup, text="OK", command=self.on_button)
        self.button.pack()

    def on_button(self):
        print(self.entry.get())

app = PopUp()
app.mainloop()

每次运行它都会收到此错误:

AttributeError: 'NoneType' object has no attribute 'get'

弹出窗口应如何工作,但其输入项似乎不起作用。 我之前已经看过这个示例,但是它不在弹出窗口中(我可以在没有弹出窗口的情况下使其完美运行)。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以将值存储在StringVar变量中,并将其存储在get()中。

import tkinter as tk
from tkinter import StringVar

class PopUp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)        
        tk.Label(self, text="Main Window").pack()
        popup = tk.Toplevel(self)
        popup.wm_title("EMAIL")
        popup.tkraise(self)        
        tk.Label(popup, text="Please Enter Email Address").pack(side="left", fill="x", pady=10, padx=10)
        self.mystring = tk.StringVar(popup)
        self.entry = tk.Entry(popup,textvariable = self.mystring, bd=5, width=35).pack(side="left", fill="x")
        self.button = tk.Button(popup, text="OK", command=self.on_button)
        self.button.pack()

    def on_button(self):
        print(self.mystring.get())

app = PopUp()
app.mainloop()