Friday, October 5, 2007

Using the Graphical System a.k.a "gs" module in Erlang

In this article, i want to present some basic usage of the graphical system otherwise known as the Erlang module "gs". The pre-requisites is the requirement for Tcl/Tk to be installed on your Linux system, otherwise you will get the error "{error,backend_died}" when you invoke the "gs:start()" and lastly include the path to your linux user so that Erlang can locate the "tk".

I have a contrived example of a simple Erlang GUI

-module(simple_window).
-export([start/0]).

start() ->
Id = gs:start(),
Win = gs:create(window, Id, [{width, 200}, {height, 100}],
Butt = gs:create(button, Win, [{label, {text, "Press Me"}}, {x, 0}]),
Butt2 = gs:create(button, Win, [{label, {text, "Stop"}}, {x, 100}]),
gs:config(Win, {map, true}),
loop(Butt, Butt2, Win).

loop(Butt, Butt2, Win) ->
receive
{gs, Butt, click, Data, Args} ->
io:format("Hello There~n", []),
loop(Butt);
{gs, Butt2, click, Data, Args} ->
gs:destroy(Win)
end.

What just happened is this
  1. A graphics server was created via the "gs:start()"
  2. A window was created with the defined width and height
  3. A button was created inside the window with a text
  4. A event-loop was created that will receive the GUI-events from the user
That's about the amount of effort u need to create a simple GUI window. The figure shows a screenshot
From the screenshot, if you keep hitting the button "Press Me" then the Erlang shell will display "Hello There" and if you hit the button "Stop" then the window will close cleanly

1 comment:

Anonymous said...

This code doesn;t compile.
You forgot ')' at line 6 and ';' at line 15.

Also, on a screenshot I see another program (that you started viw windows_2:init()).

Also, it doesn't work. When I start the program - I see nothing.