Tk Label and instance variables

B

Bart Masschelein

Hello all,

Below is a small piece of test code for a label using Tk. I try to set a
label using an instance variable, and one using a local variable. The
label with the local variable shows correctly in the window, the one
with the instance variable doesn't. I get a warning: instance variable
@value not initialized. Although the puts in between proves differently.
What is the magic between all of this?

I tried adding value to attr_reader, but that didn't solve anything. Not
that I was expecting it to.

As you probably can see, I come from a C/C++ background, and am probably
missing some Ruby fundamentals to solve this. My collection of example
scripts is rather small for the moment, and hence is also my experience.
So any directions are welcome.

gr.b.


class LabelTest
def initialize(value)
@value = value
end

def run
root = TkRoot.new { title "Label test" }

puts @value

TkLabel.new(root) do
text "#{@value}"
pack { padx 15 ; pady 15; side 'left' }
end

value2 = 200

TkLabel.new(root) do
text "#{value2}"
pack { padx 15 ; pady 15; side 'left' }
end

Tk.mainloop
end
end

test = LabelTest.new(100)
test.run
 
B

Bart Masschelein

Oh, and of course I could get around with the following, but I would
like to know why the instance variable appears to be not initialized
inside the TkLabel initialization.

value3 = @value

TkLabel.new(root) do
text "#{value3}"
pack { padx 15 ; pady 15; side 'left' }
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top