2

我有一个向用户展示组合框的功能。

def select_interface(interfaces)
  list_box :items => interfaces do |list|
    interface = list.text
  end
  ### ideally should wait until interface has a value then: ###
  return interface
end

程序的其余部分取决于此组合框中的选择。

我想找到一种方法让 ruby​​ 等待来自组合框的输入,然后执行其余代码。

鞋子里有一个类似的函数叫做ask会等待用户的输入。

interface =  ask("write your interface here")

如何在 Ruby/shoes 中实现这个“等到变量有值”功能?

4

1 回答 1

2

我花了一段时间才理解你的问题:) 我开始写一个关于 GUI 应用程序整个理论的长答案。但是你已经拥有了你需要的一切。list_box占用的块实际上是它的更改方法。你告诉它当它改变时该怎么做。当您获得所需的值时,只需推迟程序的其余部分即可运行。

Shoes.app do 
  interfaces = ["blah", "blah1", "blah2"]
  # proc is also called lambda
  @run_rest_of_application = proc do
    if @interface == "blah"
      do_blah
    # etc
  end

  @list_box = list_box(:items => interfaces) do |list|
    @interface = list.text
    @run_rest_of_application.call
    @list_box.hide # Maybe you only wanted this one time?
  end
end

这是所有 GUI 应用程序背后的基本思想:构建初始应用程序,然后等待“事件”,这将为您创建新的状态来响应。例如,在 ruby​​-gnome2 中,您将使用带有Gtk::ComboBox的回调函数/块来更改应用程序的状态。像这样的东西:

# Let's say you're in a method in a class
@interface = nil
@combobox.signal_connect("changed") do |widget| 
  @interface = widget.selection.selected
  rebuild_using_interface
end

即使在工具包之外,您也可以使用 Ruby 的Observer 模块获得“免费”事件系统。希望这有帮助。

于 2008-12-21T21:21:38.423 回答