Tkinter Entry Widget不会返回文本

时间:2015-10-10 14:03:32

标签: tkinter python-3.4

我一直在尝试学习tkinter过去几天(在python 3中),最近我试图通过入口工具从窗口获取用户输入,我可以在我打印后立即打印工具的内容我创建了小部件。但是,当我尝试在按钮调用的方法中打印时,它表示未定义Entry的名称。感谢任何帮助。谢谢。

from tkinter import *

class Window(Frame):

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

        self.init_window()

    def init_window(self):
        #Sets the title of the GUI
        self.master.title("Stuff")

        #Starts Packing shit in
        self.pack(fill="both", expand=1)

        #Adding a place for entry
        e = Entry(self)

        e.place(x=10, y=50)
        e.insert(0, "Default Val")

        #Creation of a Button
        qButton = Button(self, text="Herro", command=self.printEntry())
        qButton.place(x=10, y=10)

        #Making a menu
        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        #Creating an instance of menubar and calling it stuff
        stuff = Menu(menubar)

        #Adding the button to cascade the other options
        menubar.add_cascade(label="Stuff", menu=stuff)

        #Adding options under that cascade
        stuff.add_command(label="Herro", command=self.closeWindow)

        #Creating another 'menu' in the menu menubar
        stuff2 = Menu(menubar)
        #Adding the cascade option for stuff2 to menubar
        menubar.add_cascade(label="Other Stuff", menu=stuff2)
        #Adding the command Working to stuff2
        stuff2.add_command(label="Working", command=self.closeWindow)

    def closeWindow(self):
        exit()

    def printEntry(self):
        print(e.get())

root = Tk()
root.geometry("400x300")

app = Window(root)
root.mainloop()

以下是错误消息:

Traceback (most recent call last):
  File "tkmenu.py", line 57, in <module>
    app = Window(root)
  File "tkmenu.py", line 9, in __init__
    self.init_window()
  File "tkmenu.py", line 25, in init_window
    qButton = Button(self, text="Herro", command=self.printEntry())
  File "tkmenu.py", line 52, in printEntry
    print(e.get())
NameError: name 'e' is not defined

1 个答案:

答案 0 :(得分:1)

e是一个局部变量,因此您只能在创建它的函数中访问它。如果要在其他方法中使用该变量,请将其重命名为self.e或类似名称。