0

I think I'm having trouble with the syntax for how an object refers to itself, specifically when used in Tk callbacks. Sample code:

class MyDialog
   def initialize
      @self = self
   end

   def makeButton          
      TkButton.new(myFrame) do
         text "Do Cool Stuf"
         command @self.buttonCallback
         pack('side'=>'top')
      end
   end

   def buttonCallback
       // stuff
   end
end

This seems just fine, but when I click on the button, I get an error saying

NoMethodError: undefined method `buttonCallback' for nil:NilClass

How do I make the button press call into the instance of MyDialog that created it?

Joe Gibbs
  • 144
  • 1
  • 12
  • do you need to use @self here? I'm not familiar with Tk but `command buttonCallback` seems like it would be valid. – Anthony May 24 '15 at 22:16
  • I have tried that, but it does not work either. I get an error which says that `buttonCallback` is an unknown method in `TkButton`. – Joe Gibbs May 24 '15 at 23:29
  • If I move the definition of `butonCallback` outside the definition of `class MyDialog` then it works. But then `buttonCallback` is not a method on the class, right? – Joe Gibbs May 24 '15 at 23:39

1 Answers1

0

This question was similar to Ruby + Tk command binding - scope issue? and the answer gave me the clue I needed to make it work.

def makeButton          
  myself = @self
  TkButton.new(myFrame) do
     text "Do Cool Stuf"
     print "DEBUG: self=#{self} @self=#{@self} myself=#{myself}\n"
     command(proc{myself.buttonCallback})
     pack('side'=>'top')
  end
end

For reference, here is what the debug printed:

DEBUG: self=#<Tk::Button:0x3db6468> @self= myself=#<ManualEntry:0x2274690>
Community
  • 1
  • 1
Joe Gibbs
  • 144
  • 1
  • 12