Referring to self in Ruby/Tk

时间:2015-05-24 22:03:19

标签: ruby tk

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?

1 个答案:

答案 0 :(得分:0)

这个问题与Ruby + Tk command binding - scope issue?类似,而answer给了我使其成功的线索。

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

供参考,这是调试打印的内容:

DEBUG: self=#<Tk::Button:0x3db6468> @self= myself=#<ManualEntry:0x2274690>