Re: Ruby/Tk: How to access surrounding class from Tk Callback?
- From: Hidetoshi NAGAI <nagai@xxxxxxxxxxxxxxxx>
- Date: Tue, 28 Feb 2006 00:13:47 +0900
From: u235321044@xxxxxxxxxxxxxxxxxxxxxxxxxxx (Ronald Fischer)
Subject: Ruby/Tk: How to access surrounding class from Tk Callback?
Date: Mon, 27 Feb 2006 21:18:35 +0900
Message-ID: <l.1141041120.1069274902@xxxxxxxxxxxxxxxxxxxxxxxxx>
@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 <TkWidget-class>.new method is
evaluated by <the widget>.instance_eval(<the block>).
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@xxxxxxxxxxxxxxxx)
.
- References:
- Ruby/Tk: How to access surrounding class from Tk Callback?
- From: Ronald Fischer
- Ruby/Tk: How to access surrounding class from Tk Callback?
- Prev by Date: Re: Thinking out of the box
- Next by Date: Re: Ruby Whitespace Semantics
- Previous by thread: Ruby/Tk: How to access surrounding class from Tk Callback?
- Next by thread: Ruby path for SVN log XML -> HTML
- Index(es):
Loading