0

I am new to Tkinter and I have already troubleshot by simplifying my class, and also reading this other question on stack: "Why is Tkinter Entry's get function returning nothing?" and neither have helped.

I want to call a function that uses the entry.get() method to print the user input to the console.

from tkinter import *

class UserInterface:
    def __init__(self, master):
        lbl1 = Label(root, text="Enter graph size:")
        lbl1.grid(row=1, sticky=E)

        entry1 = Entry(root)
        entry1.grid(row=1, column=5)
        
        printButton = Button(root, text="Print")
        printButton.bind("<Button-1>", self.printSize)
        printButton.grid(row=2,column=10)

      
    def printSize(self, event):
        print("Testing: " + self.entry1.get())

root = Tk()
c = UserInterface(root)
root.geometry('500x500')
root.title('Tkinter Testing')
root.mainloop()

Here's the full exception thrown:

Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1547, in __call__
    return self.func(*args)
  File "testing.py", line 21, in printSize
    print("Testing: " + self.entry1.get())
AttributeError: UserInterface instance has no attribute 'entry1'
Garrett
  • 319
  • 1
  • 13

1 Answers1

1

There's no self.entry1 because you never defined self.entry1. You only did entry1 = Entry(root), when that should have been self.entry1 = Entry(root). The only time that not explicitly writing self will work for that is if you define something inside the class, but outside of init or any other function, like:

class UserInterface:
    entry1 = None # accessible via self.entry1
    def __init__(self, master):
        ...
        self.entry1 = Entry(root)
        ...
Random Davis
  • 6,662
  • 4
  • 14
  • 24