1

I am trying following code:

from tkinter import *

root = Tk()

class mainclass():
    def myexit(self):
        exit()
    Label(root, text = "testing").pack()
    Entry(root, text="enter text").pack()
    Button(root, text="Exit",command=self.myexit).pack()

mainclass()
root.mainloop()

On running I am getting following error:

  File "baseclass_gui.py", line 6, in <module>
    class mainclass():
  File "baseclass_gui.py", line 11, in mainclass
    Button(root, text="Exit",command=self.myexit).pack()
NameError: name 'self' is not defined

How do I define self for a button command?

Edit:

The reason I want to put this in a class is this: I was using pyreverse which is now a part of pylint and that shows diagrammatic relation between different classes. It seems to skip code that is run at main module level, hence I want to put that also in a class. See https://www.logilab.org/blogentry/6883

I find following code works:

root = Tk()
class mainclass():
    def myexit(): # does not work if (self) is used; 
        exit()
    Label(root, text = "testing").pack()
    Entry(root, text="enter text").pack()
    Button(root, text="Exit",command=myexit).pack()

mainclass()
root.mainloop()

Is there anything wrong in using this code?

1 Answer 1

3

You can't refer to self on the class level, since the object hasn't been instantiated then.

Try putting those statements in the __init__ method instead:

from tkinter import *

root = Tk()

class mainclass():

    def myexit(self):
        exit()

    def __init__(self):
        Label(root, text = "testing").pack()
        Entry(root, text="enter text").pack()
        Button(root, text="Exit",command=self.myexit).pack()

mainclass()
root.mainloop()

While removing the self from the function arguments does work, you're left with a static method that isn't related to the class it's in. It's more Pythonic to leave the function in the global scope in that case:

from tkinter import *

root = Tk()

def myexit():
    exit()

class mainclass():

    Label(root, text = "testing").pack()
    Entry(root, text="enter text").pack()
    Button(root, text="Exit",command=myexit).pack()

mainclass()
root.mainloop()
Sign up to request clarification or add additional context in comments.

2 Comments

Good answer. Pl see edit in my question above. Is the new code added OK or if not, why not?
@rnso I wouldn't define a class for no reason, though. If you're just going to instantiate it once to run your main program/loop, there's no difference between making a class and just running the program on the main module level.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.