I'm trying to run the below script to capture text entered by a user into a form using tkinter.
from tkinter import *
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_window()
# create init window
def init_window(self):
self.master.title("Example Title")
self.pack(fill = BOTH, expand = 1)
#submit button
submitButton = Button(self, text = "submit", command = self.showEntry).grid(row = 6, column = 1, sticky = W, pady = 5)
# entry widgets
Label(self, text = "Firstname").grid(row = 0)
Label(self, text = "Surname").grid(row = 1)
Label(self, text = "Age").grid(row = 2)
Label(self, text = "Gender").grid(row = 3)
e1 = Entry(self)
e2 = Entry(self)
e3 = Entry(self)
e4 = Entry(self)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)
# show entries
def showEntry(self):
txt = e1.get()
print("Firstname is %s" % txt)
root.destroy()
root = Tk()
root.geometry("400x300")
app = Window(root)
app.mainloop()
When doing so the below NameError occurs:
NameError: name 'e1' is not defined
I am very new to tkinter, so any help in how to get the text entered by the user, and why this error is occurring would be greatly appreciated.
Thanks
It is not tkinter
but OOP
problem.
You have to use self.
to create variable which exists in all methods in class
self.e1 = Entry()
and later
self.e1.get()
Currently e1
is local variable which exists only in init_window