PYTHON TkInter – setting and accessing entry widget text as variable

Question:

Ive tried reading as many articles about this as i can, but cannot find anything that helps me. In my code, i have created a class EntryWidget which has an entry widget amongst other things in it, and in my main class Controller for the app, i have created an instance of the class EntryWidget called self.entry. I am trying to write a method which will be a command for an ok button, which primarily takes the text from the entry widget and then manipulates it. this code is from the main class Controller:

     def ok(self):
         self.input = self.entry.get()
         self.command = ""

error:

     AttributeError: EntryWidget instance has no attribute 'get'

the idea is that text is entered, then the ok button is hit which calls this method. sorry if this has been asked before, but i have read the other responses and they dont help.

thanks

Asked By: chris

||

Answers:

If your EntryWidget class doesn’t subclass Tkinter.Entry, you will need to define get() method for your EntryWidget class. The error says that self.entry is a EntryWidget instance but does not contain get() method.

Answered By: K Z

I wrote myself a small function that allows the user to enter a value into a tkinter.Entry, and then function returns the user’s input.

def getInput(title, message):
    class inputGUI(tkinter.Tk):
        def __init__(self):
            tkinter.Tk.__init__(self)
            self.title(title)
            self.l=tkinter.Label(self,text=message, width = 30, pady = 10, padx = 5).pack()
            self.e=tkinter.Entry(self, width = 30)
            self.e.pack()
            self.e.focus()
            self.gap=tkinter.Label(self,text="", width = 50, pady = 0, padx = 5).pack()
            self.b=tkinter.Button(self,text='Submit',command=self.cleanup, width = 20, pady = 10, padx = 5).pack()
            self.gap=tkinter.Label(self,text="", width = 30, pady = 0, padx = 5).pack()
        def cleanup(self):
            self.userInput=self.e.get()
            self.destroy()
    root = inputGUI()
    root.focus()
    root.wait_window(root)
    valueOut = root.userInput
    return valueOut

Note: I’m aware there is no entry validation, however this should be easy enough to add.

Answered By: oliversarfas

Seems to me if your class subclassed Entry, you could use all methods from Entry. Such as .get(). Or define a tk StringVar() and then use it’s .get() and .set() methods. You can think of an Entry Widget as a small tk Text widget so some things, such as delete( e.g. myEnt.delete(1.0,END) work the same.

Answered By: dday52
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.