close
最近無聊想寫點小程式.. 可是不想用Visual Basic寫,用Ruby + GUI Toolkit寫
可是該選哪套GUI Toolkit? 說真的.. GTK+好難用喔ˊˋ.. Qt完完全全不想用
WindowsAPI? 那我乾脆用VB就好了=..=
選來選去看來看去.. 乾脆就看了godfat的建議,去玩wxWidgets
wxWidgets在Ruby上的binding叫做WxRuby,我們先來做準備吧。
首先,我們要安裝wxWidgets跟WxRuby
連線到http://www.wxwidgets.org/下載wxWidgets
接著打開命令提示字元,輸入gem i wxruby -y
一切搞定後,就可以開始先來寫個"哈囉握的"
開啟irb,輸入以下程式碼

require 'rubygems'
require 'wx'
include Wx # => 我比較懶XD

class HelloWorld < App
  def on_init #=> on_init override
    helloframe = Frame.new(nil, -1, "HelloWorld")
    StaticText.new(helloframe, -1, "Wa ha ha")
    helloframe.show
  end
end

HelloWorld.new.main_loop

在wxWidgets中,每個視窗都是一個Frame,而StaticText則是Label(在VB中就叫做Label,SWT我不知道XD)
Okok.. 可以動對不對? 不能動那就.. (( 當作沒看到

繼續...
或許各位會認為很奇怪,為什麼要自己慢慢寫.. 不要用視覺化的開發工具呢?
現在來跟各位介紹,在GTK中有所謂的Glade,那在wxWidgets呢?當然有wxGlade!
如果不喜歡wxGlade,這邊也有列表:[網址太長請點我]
在wxWidgets中,支援一種叫做XRC(XML Resource)的格式檔案,很多視覺化工具,如wxGlade都支援輸出這種檔案。
這種檔案的好處是不管是哪種開發工具或者程式語言,都可以藉由這個XRC檔案來產生一樣的介面。
各位可以到http://wxglade.sourceforge.net/下載wxGlade,安裝後就可以開始拖拉了。
弄好一個介面後,我們選擇產生XRC檔案。
接著在同個目錄下,新增一個.rb檔案。
假設我們有一個Frame與一個Button
Frame: MainFrame
Button: btnButton
程式碼如下

require 'rubygems'
require 'wx'
include Wx

class MainFrame < Frame
  def initialize
    super
    $xml.load_frame_subclass(self, nil, 'MainFrame')
    # load_frame_subclass是用來讀取XRC檔案中的Frame
    # 如果要用load_frame_subclass,則必須呼叫super且不帶參數
    @btn = find_window_by_id(xrcid('btnButton'))
    evt_button(@btn.get_id){
      message_box("Hello World!!!")
    }
  end
end

class Main < App
  def on_init
    $xml = XmlResource.get
    $xml.init_all_handlers
    xrc_file = File.join(File.dirname(__FILE__), "test.xrc")
    $xml.load(xrc_file)
    main = MainFrame.new
    main.show(true)
  end
end

Main.new.main_loop

OK,大致上就這樣囉..
arrow
arrow
    全站熱搜

    hechian 發表在 痞客邦 留言(0) 人氣()