A gWidget Example - Using windows, groups, labels, text and password boxes, buttons and events in R
In this entry, a short example for using gWidgets is given. gWidgets is a package for creating GUI’s in R.
Our example shows a GUI window with width = 400 and height = 400. Window is created by gwindow function. Components are located by rows. Rows are handled by ggroup function. ggroup must take a container as a parameter. In this logic, lbl_username and txt_username are childs of row1 which is child of gwindow.
Any text field can act as a password field by using visible¡- function.
So, the object txt_password is now hiding characters by * characters. Finally, the method addHandlerClicked links an object to a function for click event. In our example, btn_login is linked to do_login function. When btn_login clicked, a message is written. The source code of the complete example is given below.
1# Loading required packages
2require("gWidgets")
3require("gWidgetstcltk")
4
5# main window
6main <- gwindow(title="Login␣Window",
7 width=400,
8 height=400)
9
10# a row and components
11row1 <- ggroup(container=main)
12lbl_username <- glabel(container=row1, text="Username:␣")
13txt_username <- gedit(container=row1)
14
15
16# a row and components
17row2 <- ggroup(container=main)
18lbl_password <- glabel(container=row2, text="Password:␣")
19txt_password <- gedit(container=row2)
20
21# any text in txt_password will be show with * character
22visible(txt_password) <- FALSE
23
24# a row for button
25row3 <- ggroup(container=main)
26btn_login <- gbutton(container=row3,
27 text="Login")
28btn_register <- gbutton(container=row3,
29 text="Register")
30
31
32# Event handler for login button
33do_login <- function(obj){
34 cat("Login␣with␣",svalue(txt_username),"\n")
35}
36
37# Event handler for register button
38do_register <- function(obj){
39 cat("Register␣with␣", svalue(txt_username),"\n")
40}
41
42
43# Registering Events
44addHandlerClicked ( btn_login, do_login)
45addHandlerClicked ( btn_register, do_register)