O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

21.14. Creating a GUI Application with wxRuby

Problem

You want to write a portable GUI application that looks better than a Tk application.

Solution

Use the wxRuby library, available as a third-party download. It uses native GUI widgets on Windows, Unix, and Mac OS X. It's got many more features than the Tk library, and even greater complexity.

Here's a very simple wxRuby application (Figure 21-3):

	#!/usr/bin/ruby -w
	# wxtrout.rb

	require 'wxruby'
	class TroutApp < Wx::App
	  def on_init
	    frame = Wx::Frame.new(nil, -1, 'Tiny wxRuby Application')
	    panel = Wx::StaticText.new(frame, -1, 'You are a trout!',
	                               Wx::Point.new(-1,1), Wx::DEFAULT_SIZE,
	                               Wx::ALIGN_CENTER)
	    frame.show
	  end
	end

	TroutApp.new.main_loop
You are a wxRuby trout

Figure 21-3. You are a wxRuby trout

Discussion

The simple wxRuby application has the same basic structure as its Tk cousin (see Recipe 21.12). A top-level widget is created (here called a Frame) and a label (StaticText) widget is added to it. The application then goes into an event loop, listening for and retrieving events like mouse clicks.

A wxRuby version of the Tk stopwatch program is also similar, although much longer. wxRuby code tends to be more verbose and less idiomatic than Ruby Tk code.

The core methods are nearly unchanged, because they have little to do with the GUI:

 #!/usr/bin/ruby -w # wx_stopwatch.rb require 'wxruby' class StopwatchApp < Wx::App def start @start = Time.now @button.set_label('Stop') ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required