Search code examples
pythonbuttontkintercommandself

Python Tkinter passing self as button command parameter


I have a noob question:

I am trying to make a class "Field" that inherits everything from Tkinter's Button class but also contains the additional attribute "location" and a method to get that attribute. Having implemented that, I make in instance of the new "Field" class and try to have the Field's command call its function to get its location attribute:

from Tkinter import *

class Field(Button):
    def __init__(self, location, **k):
        Button.__init__(self, **k)
        self.location = location

    def getLoc(self):
        return self.location

root=Tk()
c = Field(2, text="Text", command = lambda: self.getLoc)
c.pack()
root.mainloop()

The root window with the button appears but upon pressing it, the following error occurs:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "C:\Users\PC\Desktop\test2.py", line 12, in <lambda>
    c = Field(2, text="Text", command = lambda: self.getLoc)
NameError: global name 'self' is not defined

What should I do to make it see the fact that I want the recently instantiated "Field" to be the "self" whose location it should return?

Thank you in advance


Solution

  • Edit: sorry I was completely off about the original response about doing lambda self: self.getLoc, corrected answer (and checked by running the code this time!)

    You should probably configure the command after you create the button, that way you can explicitly refer to the button.

    root=Tk()
    c = Field(2, text="Text")
    c.config(command=c.getLoc)
    c.pack()
    root.mainloop()    
    

    You can read more about the config method of Tkinter objects (and much more) on effbot.org.