3

I'm trying to use glade3 with Ruby, but unfortunately examples of this are few and far between. Looking at what's available, I've come up with the following code, but there's still something missing, as the window does not display. There doesn't seem to be any GtkBuilder 'show' method, so I'm not sure what's needed to make it appear. Does anyone know what I need to do to make this work?

"hello.xml" is just a fairly simple glade3 xml file with a GtkWindow and a button.

#!/usr/bin/env ruby

require 'rubygems'
require 'gtk2'

class HelloGlade
  attr :glade

  def initialize
    if __FILE__ == $0
      Gtk.init
      builder = Gtk::Builder::new
      builder.add_from_file("hello.xml")
      builder.connect_signals{ |handler| method(handler) }  # (I don't have any handlers yet, but I will have eventually)
      Gtk.main()
    end
  end

  def gtk_main_quit
    puts "Gtk.main_quit"
    Gtk.main_quit()
  end
end


hello = HelloGlade.new

hello.xml:

<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <requires lib="gtk+" version="2.24"/>
  <!-- interface-naming-policy project-wide -->
  <object class="GtkWindow" id="window1">
    <property name="can_focus">False</property>
    <child>
      <object class="GtkButton" id="button1">
        <property name="label" translatable="yes">button</property>
        <property name="visible">True</property>
        <property name="can_focus">True</property>
        <property name="receives_default">True</property>
        <property name="use_action_appearance">False</property>
      </object>
    </child>
  </object>
</interface>

(edit)

Ugh, it's always the way. Post a question, and I figure out the answer for myself. I needed to get the window1 object from the GtkBuilder, and call its show() method:

...
window = builder.get_object("window1")
window.show()
Gtk.main
4

1 回答 1

0

如果您使用visualruby,该程序会更容易编写。这就是您的代码的样子:

class HelloGlade

  include GladeGUI

  def initialize
    load_glade(__FILE__)
    show_window()
  end

end

您无需设置“可见”属性,也无需编写代码来关闭窗口或连接信号。一切都是自动完成的。这里有很多例子:

http://visualruby.net

于 2012-03-25T06:02:20.620 回答