0

Here is the code:

#!/usr/bin/python
from tkinter import *

class App:
    def _init_(self, master):

        frame = Frame(master)
        frame.pack()

    self.lbl = Label(frame, text = "Hello World!\n")
    self.lbl.pack()

    self.button = Button(frame, text="Quit", fg="red", command=frame.quit)
    self.button.pack(side=LEFT)

    self.hi_there = Button(frame, text="Say hi!", command=self.say_hi)
    self.hi_there.pack(side=LEFT)

    def say_hi(self):
        print("Hello!")

    root = Tk()
    root.title("Hai")
    root.geometry("200x85")
    app = App(root)
    root.mainloop()

And here, the error:

Traceback (most recent call last):
  File "F:/HTML/HTMLtests/python/hellotkinter2.py", line 4, in <module>
    class App:
  File "F:/HTML/HTMLtests/python/hellotkinter2.py", line 10, in App
    self.lbl = Label(frame, text = "Hello World!\n")
NameError: name 'frame' is not defined

Can't find where it went wrong! Appreciate any helps!

2 Answers 2

4

There's quite a bit wrong here:

  1. It's __init__, not _init_.
  2. You should learn the difference between class member variables (not set in __init__), and instance member variables (set in __init__). You're using self entirely wrong.
  3. Your class appears to recursively instantiate itself??
  4. You should separate concerns instead of having one giant formless class that does the whole shebang.

Your error is due to 2 but will not be completely resolved until you have a look at 1 and 3.

Sign up to request clarification or add additional context in comments.

Comments

1

Indentation and capitalization is off along w/ some underscores. The following works.

#!/usr/bin/python
from Tkinter import *

class App(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.lbl = Label(frame, text = "Hello World!\n")
        self.lbl.pack()

        self.button = Button(frame, text="Quit", fg="red", command=frame.quit)
        self.button.pack(side=LEFT)

        self.hi_there = Button(frame, text="Say hi!", command=self.say_hi)
        self.hi_there.pack(side=LEFT)

    def say_hi(self):
        print("Hello!")

root = Tk()
root.title("Hai")
root.geometry("200x85")
app = App(root)
root.mainloop()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.