使用Tk的GUI:如何根据输入创建2个不同的tk标签

时间:2014-05-06 06:37:06

标签: ruby tk

我有一个这样的脚本:

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

问题是我可以调用的唯一方法是使用Tk.mainloop,然后它将同时调用root1和root2变量并形成文本'第一个例子' &安培; '第二个例子'在一个消息框中。

1 个答案:

答案 0 :(得分:0)

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