Hmmm… There are some problems.
From: “Jeppe J.” [email protected]
Subject: Re: Q about tk buttons
Date: Thu, 13 Apr 2006 22:33:18 +0900
Message-ID:
[email protected]
require “tk”
#methods
def guess
if (guess.value == right_guess.value)
status.value = “Correct!”
else
number_of_guess.numeric += 1
status.value = “Sorry, no luck”
end
end
Probably, you’ll want to refer local variables on main.
But those variables are out of scope in the method.
If arguments bothers you, you can use a Proc object instead of a method.
Next, please see here.
def guess
^^^^^
guess = TkVariable.new()
^^^^^
There is conflict of names.
So, “proc{guess}” refers the local variable.
If you want to call “guess” method, you must use “proc{guess()}”.
root = Tk.mainloop
Probably, the return value is not useful.
If I were you, I may write such like as the following.
require ‘tk’
right_guess = rand(21)
number_of_guess = TkVariable.new(0)
Tk.root.title(‘Number guess’)
TkLabel.new(:textvariable=>number_of_guess).pack(:side=>:top,
:pady=>10)
status = TkLabel.new(:text=>“Entry your guess and press the button”,
:width=>37).pack(:side=>:bottom, :pady=>10)
entry = TkEntry.new.pack(:side=>:top, :pady=>10)
guess_cmd = proc{
value = entry.value
if value.empty? || value.to_i != right_guess
number_of_guess.numeric += 1
status.text(‘Sorry, no luck’)
else
status.text(‘Correct!’)
end
}
button = TkButton.new(:text=>‘Guess’,
:command=>guess_cmd).pack(:side=>:top, :p\ady=>10)
entry.bind(‘Return’, proc{button.invoke})
Tk.mainloop