1

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

1 Answer 1

3

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.

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

2 Comments

Thanks! It helped. I guess it makes sense, since the "self" doesn't really exist yet when I am trying to pass the command during the Field instantiation. Also thank you for the config info, definitely going to come in handy. (My apologies for lack of +1, cannot do due to low reputation :()
Hello there! I am experiencing a similar issue but for a button, not a field. When I tried the code above, replacing the Fields with Buttons, I got an error saying that the buttons don't have the getLoc property. Can somebody guide me in the right direction? Thanks!

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.