-1

This is just a simple practice of Python Tkinter. Here is the code:

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):
        self.master.title('GUI')
        self.pack(fill=BOTH, expand=1)

        text = Entry(self, bd=1)
        text.pack(side = TOP)

        submit_b = Button(self, text = 'submit', command = self.submit)
        submit_b.pack(side = BOTTOM)
    def submit(self):
        print(self.text.get())

root = Tk()
root.geometry('200x50')

app = Window(root)

root.mainloop()

The result is like this:

enter image description here

So I enter a string in the 'Entry' and click 'submit' button. This program will print out the string.

However, I got this:

AttributeError: 'Window' object has no attribute 'text'

I have no idea why it didn't work. Please help me!

Mars Lee
  • 1,845
  • 5
  • 17
  • 37

1 Answers1

4

You just forgot the self in the declaration of text:

    self.text = Entry(self, bd=1)
    self.text.pack(side = TOP)

Thus text was a local variable and promptly "forgotten" after __init__ finished. This way, it is a member variable of the instance and can be accessed from within submit. Note that, other than e.g. with Java's this, Python does not automatically look for an instance variable if no local variable of the same name has been found. self is not optional or just for disambiguation.

Alternatively, you could keep text as a local variable, but make submit local, too:

    text = Entry(self, bd=1)
    text.pack(side = TOP)
    def submit():
        print(text.get())
    submit_b = Button(self, text = 'submit', command = submit)
    submit_b.pack(side = BOTTOM)

For submit_b, you do not need self, as you do not refer to that button outside of the __init__ method. In fact, after the call to pack, you do not refer to the button at all, so you could even do:

    Button(self, text = 'submit', command = submit).pack(side = BOTTOM)
Community
  • 1
  • 1
tobias_k
  • 81,265
  • 12
  • 120
  • 179