From: Hidetoshi NAGAI Date: 2006-02-28T00:13:47+09:00 Subject: Re: Ruby/Tk: How to access surrounding class from Tk Callback? From: u235321044@spawnkill.ip-mobilphone.net (Ronald Fischer) Subject: Ruby/Tk: How to access surrounding class from Tk Callback? Date: Mon, 27 Feb 2006 21:18:35 +0900 Message-ID: > @root=TkRoot.new() { title "My Form" } > action_button=TkButton.new(@root) { > text "Action!" > command { > # Do something with @root and @foo > puts @root.foo # DOES NOT WORK > } > } It may be a FAQ. A block given to .new method is evaluated by .instance_eval(). That is, in the block, 'self' is the widget object. So, @root in your button's command is an instance variable of the button widget. To avoid it, you have to give attention to scope of variables. For example, ------< example 1 >------------------------------------------ def initialize(...) foo = @foo=1234 ... root = @root = TkRoot.new() { title "My Form" } action_button=TkButton.new(@root) { text "Action!" command { # use local variables puts foo # same as @foo puts root # same as @root } } action_button.pack("side" => "right"); end ------------------------------------------------------------- ------< example 2 >------------------------------------------ def initialize(...) @foo=1234 ... @root = TkRoot.new() { title "My Form" } action_button=TkButton.new(@root, :text=>"Action!", :command=>proc{ puts @foo puts @root }) action_button.pack("side" => "right"); end ------------------------------------------------------------- ------< example 3 >------------------------------------------ def initialize(...) @foo=1234 ... @root = TkRoot.new() { title "My Form" } cmd = proc{ puts @foo puts @root } action_button=TkButton.new(@root) { text "Action!" command cmd } action_button.pack("side" => "right"); end ------------------------------------------------------------- -- Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)