Home > Net >  Ruby TK how to receive input from user?
Ruby TK how to receive input from user?

Time:11-05

I am new to Ruby and I would like to receive input from users with Ruby TK. The Internet has too little information about this. So I am here to search for a solution. Below is the current method that I am using.

TkSpinbox.new(left) do
    to 100
    from 1
    value = TkVariable.new()
    increment value  = 1
    command (proc{
        puts value
    })
    pack("side" => "bottom",  "padx"=> "50", "pady"=> "54")
end

I have no idea how to get the value inside the spinbox and return it to another place. This is the screenshot of the GUI. enter image description here

CodePudding user response:

There are a couple of little changes you can make to that code snippet which will let you access the spinbox value correctly:

  1. The increment method takes one argument, the amount to increment the value by every time you click a button. So you can replace increment value = 1 with just increment 1.

  2. You don't need the value = TkVariable.new() line, because the TkSpinbox keeps track of its value itself. (If you did want to set an initial value, you would use e.g. self.value = 10.)

After making those changes, this is the final code snippet:

TkSpinbox.new(left) do
    to 100
    from 1
    increment 1

    # Equivalent to your proc({...}) usage here, but this is better Ruby style
    command do
        puts value
    end
    pack("side" => "bottom",  "padx"=> "50", "pady"=> "54")
end

And here's how it looks when you click the increment button several times:

enter image description here

To use the value from some other control like a button, you can assign your TkSpinbox to a variable and access its value from another command block:

# Assign spinbox to a variable named `spinbox`
spinbox = TkSpinbox.new(left) do
    to 100
    from 1
    increment 1
    command do
        puts value
    end
    pack("side" => "bottom",  "padx"=> "50", "pady"=> "54")
end

TkButton.new(left) do
    text "Do something with the value"
    command do
        # Now `spinbox` is usable from other controls
        # (The value may be a string, so we use .to_i to convert to an integer)
        puts spinbox.value.to_i * 100
    end
    pack("side" => "top")
end
  • Related