Question

I have a script like this:

require 'tk'

root = TkRoot.new { title "Example 1" }
TkLabel.new(root) do
   text 'First example'
   pack { padx 15 ; pady 15; side 'left' }
end

root1 = TkRoot.new { title "Example 2" }
TkLabel.new(root1) do
   text 'Second example'
   pack { padx 15 ; pady 15; side 'left' }
end

class Test
  def run
    puts "Enter 1 or 2"
    i = gets
    if i == "1"
      #run the root variable with Example 1
    else
      #run the root1 variable with Example 2
    end
  end
end

init = Test.new
init.run

Problem is the only way I can call is using Tk.mainloop and then it will call both root1 and root2 variables together and forms both the text 'First example' & 'Second example' in one messagebox.

Was it helpful?

Solution

require 'tk'

class Foo 
  def initialize
    root = TkRoot.new { title "Example 1" }
    TkLabel.new(root) do
       text 'First example'
       pack { padx 15 ; pady 15; side 'left' }
    end
    Tk.mainloop
  end
end

class Boo
  def initialize
    root1 = TkRoot.new { title "Example 2" }
    TkLabel.new(root1) do
       text 'Second example'
       pack { padx 15 ; pady 15; side 'left' }
    end
    Tk.mainloop
  end
end

class Test
  def run
    puts "Enter 1 or 2"
    i = gets
    if i == "1"
      a = Foo.new
    else
      b = Boo.new
    end
  end
end

init = Test.new
init.run
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top