rnso
rnso

Reputation: 24535

Cannot use Python class function as button command

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?

Upvotes: 1

Views: 65

Answers (1)

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()

Upvotes: 3

Related Questions