Hello, World! Simple Widgets Binding Events More Widgets Scrollbars Menus Canvas Make things look Beautiful More Information

We are moving to this wiki

Hello, world!

Let's start with a very simple Hello World, before we dive deep into Ruby/Tk. To use Tk, start with
irb> require 'tk'
We will not reprint this statement in all other chapters.

Tk isn't very difficult, but it has its habits. Like all toolkits, you need something called a ``root'' before you will be seeing anything. Actually, it is a root window, which is probably what you would simply call a window. Windows can have a title. So let's do this:

irb> root = TkRoot.new() { title "Hello, world!" }
Hm, still don't see anything.

A useful thing about toolkits is that they pass events from mouse, keyboard and such to you. When you think about it, it is quite logical: widgets receive the events from X (or whatever GUI your OS uses), but must receive them first, before passing them to every listener subscribed to the widget. Most toolkits use a thread to listen to those events. Let's start the Tk thread:

irb> Tk.mainloop()
Voilà! a window with the title ``Hello, world''! What more do you want? (NB: If you can not read the window title, enlarge the window.)

You might have noticed that the irb prompt does not come back. Ruby is waiting for the Tk thread to end. Since there is not much we can do now, click on the kill-button of the window (in order to destroy it; the button is provided by your window manager). You will see that the window actually disappears (like many toolkits) and the irb prompt returns (which means the Tk thread has ended, unlike most toolkits).

Play it Again, Sam!

Let's type the above again, all of it (you didn't leave irb already, did you?)
irb> require 'tk'
irb> root = TkRoot.new() { title "Hello, world!" }
irb> Tk.mainloop()
The first line does not do anything anymore, because the required scripts (and shared libraries) are already loaded. If you'd ever wish to force a reload, you can use load.

The second line does not complain (but subsequent commands, as used in later chapters) would.

The third line fails to show a window again! You can not run the Tk.mainloop again, too bad. Unfortunately, I do not know why, so we simply have to live with it...

Run Scripts

Now that running from irb is a bit less useful, we will run scripts with Ruby itself (or at least not print the irb> anymore :-)
require 'tk'
root = TkRoot.new() { title "Hello, world!" }
Tk.mainloop()

Hello, World! Simple Widgets Binding Events More Widgets Scrollbars Menus Canvas Make things look Beautiful More Information

Kero