PyGTK – ComboBox Class

PyGTK – ComboBox Class ”; Previous Next ComboBox is a powerful and popular widget in any GUI toolkit. It provides a dropdown list of items from which a user can choose. The gtk.ComboBox widget implements the CellLayout interface and provides a number of methods to manage the display of items. The object of gtk.ComboBox class is associated with a ListSore, which is a list model that can be used with widgets that display collection of items. Items are added to ListStore with the append() method. Further, a CellRendererText object is created and packed into the combobox. Follow these steps to set up a combobox. combobox = gtk.ComboBox() store = gtk.ListStore(gobject.TYPE_STRING) cell = gtk.CellRendererText() combobox.pack_start(cell) combobox.add_attribute(cell, ”text”, 0) PyGTK offers a convenience method — gtk.combo_box_new_text() to create a combo box instead of using a list store. Associated convenience methods append_text(), prepend_text(), insert_text() and remove_text() are used to manage the combo boxcontents. gtk.ComboBox class has the following methods − S.NO Methods and Description 1 set_wrap_width() Sets the number of columns to be displayed in the popup table layout 2 get_active() Returns the value of the “active” property which is the index in the model of the currently active item 3 set_active() Sets the active item of the combo_box to the item with the model index specified 4 set_model() Sets the model used by the combo box 5 append_text() Appends the string specified by text to the list of strings stored in the combo box list store 6 Insert_text() Inserts the string specified by text in the combo box gtk.ListStore at the index specified by position 7 prepend_text() Prepends the string specified by text to the list of strings stored in the list store 8 remove_text() Removes the string at the index specified by position in the associated liststore 9 get_active_text() Returns the currently active string The ComboBox widget emits the following signals − changed This is emitted when a new item in the combo box is selected move_active This is a keybinding signal which gets emitted to move the active selection. Popdown This is a keybinding signal which gets emitted to popdown the combo box list. The default bindings for this signal are Alt+Up and Escape Popup This is a keybinding signal which gets emitted to popup the combo box list. The default bindings for this signal are Alt+Down. Two example codes for the demonstration of ComboBox are given below. Example 1 In this example, a ListStore is populated with the names of popular Python GUI toolkits and it is associated with a ComboBox widget. As a user makes a choice, the changed signal is emitted. It is connected to a callback function to display the user”s choice. import pygtk pygtk.require(”2.0”) import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“ComboBox with ListStore”) self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) combobox = gtk.ComboBox() store = gtk.ListStore(str) cell = gtk.CellRendererText() combobox.pack_start(cell) combobox.add_attribute(cell, ”text”, 0) fixed = gtk.Fixed() lbl = gtk.Label(“select a GUI toolkit”) fixed.put(lbl, 25,75) fixed.put(combobox, 125,75) lbl2 = gtk.Label(“Your choice is:”) fixed.put(lbl2, 25,125) self.label = gtk.Label(“”) fixed.put(self.label, 125,125) self.add(fixed) store.append ([“PyQt”]) store.append ([“Tkinter”]) store.append ([“WxPython”]) store.append ([“PyGTK”]) store.append ([“PySide”]) combobox.set_model(store) combobox.connect(”changed”, self.on_changed) combobox.set_active(0) self.connect(“destroy”, gtk.main_quit) self.show_all() return def on_changed(self, widget): self.label.set_label(widget.get_active_text()) return if __name__ == ”__main__”: PyApp() gtk.main() Upon execution, the program displays the following output − Example 2 The second version of the program uses the convenience method combo_box_new_text() to create a combo box and append_text() function to add strings in it. In both programs, the get_active_text() method is used to fetch user”s selection and display on a label on the window. import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“Simple ComboBox”) self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) cb = gtk.combo_box_new_text() cb.connect(“changed”, self.on_changed) cb.append_text(”PyQt”) cb.append_text(”Tkinter”) cb.append_text(”WxPython”) cb.append_text(”PyGTK”) cb.append_text(”PySide”) fixed = gtk.Fixed() lbl = gtk.Label(“select a GUI toolkit”) fixed.put(lbl, 25,75) fixed.put(cb, 125,75) lbl2 = gtk.Label(“Your choice is:”) fixed.put(lbl2, 25,125) self.label = gtk.Label(“”) fixed.put(self.label, 125,125) self.add(fixed) self.connect(“destroy”, gtk.main_quit) self.show_all() def on_changed(self, widget): self.label.set_label(widget.get_active_text()) if __name__ == ”__main__”: PyApp() gtk.main() The output of this program is similar to that of the previous program. Print Page Previous Next Advertisements ”;

PyGTK – Signal Handling

PyGTK – Signal Handling ”; Previous Next Unlike a console mode application, which is executed in a sequential manner, a GUI-based application is event driven. The gtk.main() function starts an infinite loop. Events occurring on the GUI are transferred to appropriate callback functions. Each PyGTK widget, which is derived from the GObject class, is designed to emit ‘signal’ in response to one or more events. The signal on its own does not perform any action. Instead, it is ‘connected’ to a callback function. Some signals are inherited by the widget, whereas some signals are widget specific. For example, “toggled” signal is emitted by the toggleButton widget. A signal handler is set up by invoking the connect() method of the gtk.widget class. handler_id = object.connect(name, func, func_data) The first argument, name, is a string containing the name of the signal you wish to catch. The second argument, func, is the call back function you wish to be called when it is caught. The third argument, func_data, the data you wish to pass to this function. The handler id, which is used to uniquely identify the callback method. For example, to invoke onClicked() function when a button is clicked, use the following syntax − btn.connect(“clicked”,onClicked,None) The onClicked() function is defined as − def onClicked(widget, data=None): If the callback method is an object method, it receives self as an additional argument − def onClicked(self, widget, data=None): Example In the following example, a Button is added to gtk.Window. “Hello World” message is printed when the button is clicked. import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“Hello World in PyGTK”) self.set_default_size(400,300) self.set_position(gtk.WIN_POS_CENTER) self.label = gtk.Label(“Enter name”) self.entry = gtk.Entry() self.btn = gtk.Button(“Say Hello”) self.btn.connect(“clicked”,self.hello) fixed = gtk.Fixed() fixed.put(self.label, 100,100) fixed.put(self.entry, 100,125) fixed.put(self.btn,100,150) self.add(fixed) self.show_all() def hello(self,widget): print “hello”,self.entry.get_text() PyApp() gtk.main() Run the above code from Python prompt. The following output will be displayed − When the button is pressed, the following output is displayed on the console − Hello TutorialsPoint Print Page Previous Next Advertisements ”;

PyGTK – Layout Class

PyGTK – Layout Class ”; Previous Next The gtk.Layout is a container widget similar to gtk.Fixed. Widgets are placed in Layout widget by specifying absolute coordinates. However, the Layout differs from fixed widget in the following ways − The layout widget can have infinite width and height. The maximum value of width and height is limited by the size of unsigned integer. A gtk.DrawingArea widget can be enclosed in a layout container. The DrawingArea is a canvas on which 2D elements like line, rectangle etc. can be drawn. In order to put the Layout container in the toplevel window of lesser dimensions, it can be associated with the scrollbars or can be placed in a ScrolledWindow. The gtk.Layout class has the following constructor − gtk.Layout(hadjustment = None, vadjustment = None) The hadjustment and vadjustment properties represent an object having an adjustable bounded value. The following table lists out the frequently used methods of the layout − put(widget, x, y) Places a child widget at the specified coordinates set_size(w, h) Sets the size of the Layout container to the specified width and height The Layout object emits the set_scroll_adjustment signal when the adjustments associated with it are changed. Example In the following example, a Label is paced at the centre of a Layout container, which in turn is to be placed in a toplevel window of smaller size. Hence, it is first added to a ScrolledWindow and the ScrolledWindow is then added to the main window. Observe the code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“layout”) self.set_size_request(300,200) self.set_position(gtk.WIN_POS_CENTER) sc = gtk.ScrolledWindow() lo = gtk.Layout() lo.set_size(400,400) button = gtk.Button(“Press Me”) lo.put(button, 125,200) sc.add(lo) self.add(sc) self.connect(“destroy”, gtk.main_quit) self.show_all() PyApp() gtk.main() The above code will generate the following output − Print Page Previous Next Advertisements ”;

PyGTK – Home

PyGTK Tutorial PDF Version Quick Guide Resources Job Search Discussion PyGTK is a set of wrappers written in Python and C for GTK + GUI library. It is part of the GNOME project. It offers comprehensive tools for building desktop applications in Python. This tutorial discusses the basic functionalities of the different widgets found in the toolkit. Audience This tutorial has been prepared for beginners to help them understand the basic concepts of PyGTK. Advanced programmers can also draw benefits from this tutorial. Prerequisites Before proceeding further with this tutorial, it is recommended that you have a reasonable knowledge of Python programming language. Print Page Previous Next Advertisements ”;

PyGTK – Window Class

PyGTK – Window Class ”; Previous Next An object of the gtk.Window class provides a widget that users commonly think of as a Wwindow. This widget is a container hence, it can hold one child widget. It provides a displayable area decorated with title bar and resizing controls. gtk.Window class has the following constructor − gtk.Window(type) Type paramter takes one of the following values − gtk.WINDOW_TOPLEVEL (default) This window has no parent. The Toplevel windows are the main application window and dialogs. gtk.WINDOW_POPUP This window has no frame or decorations. A popup window is used for menus and tooltips. Some of the important methods of the gtk.Window class are listed below − S.NO Methods and Description 1 set_title(string) This sets the “title” property of the gtk.window to the value specified by the title. The title of a window will be displayed in its title bar. 2 get_title() This returns the title of a window if set. 3 set_position() This sets the position of window. The predefined position constants are − gtk.WIN_POS_NONE gtk.WIN_POS_CENTER gtk.WIN_POS_MOUSE gtk.WIN_POS_CENTER_ALWAYS gtk.WIN_POS_CENTER_ON_PARENT 3 set_focus() This sets the widget specified to be the focus widget for the window. 4 set_resizable() This is true by default. set_resizable() helps the user to set the size of a window. 5 set_decorated() This is true by default. If false, the title bar and the resizing controls of window will be disabled. 6 set_modal() If true, window becomes modal and the interaction with other windows is prevented. This is used for the Dialog widgets. 7 set_default_size() This sets the default size of the window to the specified width and height in pixels. The gtk.Window widget emits the following signals − activate-default This is emitted when the default child widget of window is activated usually by the user pressing the Return or Enter key. activate-focus This is emitted when the child widget with the focus is activated usually by the user pressing the Space key. move-focus This is emitted when the focus is changed within the window”s child widgets when the user presses the Tab, the Shift+Tab or the Up, Down, Left or Right arrow keys. set-focus This is emitted when the focus changes to widget in window. Print Page Previous Next Advertisements ”;

PyGTK – Introduction

PyGTK – Introduction ”; Previous Next PyGTK is a set of wrappers written in Python and C for GTK + GUI library. It is part of the GNOME project. It offers comprehensive tools for building desktop applications in Python. Python bindings for other popular GUI libraries are also available. PyQt is a Python port of QT library. Our PyQt tutorial can be found here. Similarly, wxPython toolkit is Python binding for wxWidgets, another popular cross-platform GUI library. Our wxPython tutorial is available here. GTK+, or the GIMP Toolkit, is a multi-platform toolkit for creating graphical user interfaces. Offering a complete set of widgets, GTK+ is suitable for projects ranging from small one-off tools to complete application suites. GTK+ has been designed from the ground up to support a wide range of languages. PyGTK is a Python wrapper for GTK+. GTK+ is built around the following four libraries − Glib − A low-level core library that forms the basis of GTK+. It provides data structure handling for C. Pango − A library for layout and rendering of text with an emphasis on internationalization. Cairo − A library for 2D graphics with support for multiple output devices (including the X Window System, Win32) ATK − A library for a set of interfaces providing accessibility tools such as screen readers, magnifiers, and alternative input devices. PyGTK eases the process and helps you create programs with a graphical user interface using the Python programming language. The underlying GTK+ library provides all kinds of visual elements and utilities for it to develop full-featured applications for the GNOME Desktop. PyGTK is a cross-platform library. It is a free software distributed under the LGPL license. PyGTK is built around GTK + 2.x. In order to build applications for GTK +3, PyGObject bindings are also available. Print Page Previous Next Advertisements ”;

PyGTK – Alignment Class

PyGTK – Alignment Class ”; Previous Next This widget proves useful in controlling alignment and size of its child widgets. It has four properties called xalign, yalign, xscale and yscale. The scale properties specify how much of free space will be used by the child widgets. The align properties areused to place the child widget within available area. All four properties take up a float value between 0 and 1.0. If xscale and yscale property is set to 0, it means that widget absorbs none of free space and if set to 1, widget absorbs maximum free space horizontally or vertically respectively. The xalign and yalign property if set to 0, means that there will be no free space to the left or above widget. If set to 1, there will be maximum free space to left or above the widget. The gtk.alignment class has the following constructor − gtk.alignment(xalign = 0.0, yalign = 0.0, xscale = 0.0, yscale = 0.0) Where, xalign − Is the fraction of the horizontal free space to the left of the child widget. yalign − Is the fraction of vertical free space above the child widget. xscale − Is is the fraction of horizontal free space that the child widget absorbs. yscale − Is is the fraction of vertical free space that the child widget absorbs. Example The following code demonstrates the use of gtk.alignment widget. A Vbox in the toplevel window has an upper Vbox and lower Hbox placed in it. In the upper vertical box, a label and an Entry widget are placed such that towards the left, 50% of space is kept free and more than 25% of this is occupied by assigning 0.5 xalign and 0.25 to yalign properties. In the lower HBox, all the available free space is on the left side. This is achieved by assigning 1 to xalign property. Hence, two buttons in the horizontal box appear right aligned. import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“Alignment demo”) self.set_size_request(400,200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox(False, 5) vb = gtk.VBox() hbox = gtk.HBox(True, 3) valign = gtk.Alignment(0.5,0.25, 0, 0) lbl = gtk.Label(“Name of student”) vb.pack_start(lbl, True, True, 10) text = gtk.Entry() vb.pack_start(text, True, True, 10) valign.add(vb) vbox.pack_start(valign) ok = gtk.Button(“OK”) ok.set_size_request(70, 30) close = gtk.Button(“Close”) hbox.add(ok) hbox.add(close) halign = gtk.Alignment(1, 0, 0, 0) halign.add(hbox) vbox.pack_start(halign, False, False, 3) self.add(vbox) self.connect(“destroy”, gtk.main_quit) self.show_all() PyApp() gtk.main() The above code produces the following output − Print Page Previous Next Advertisements ”;

PyGTK – Button Class

PyGTK – Button Class ”; Previous Next The gtk.Button widget is usually displayed as a pushbutton with a text label. It is generally used to attach a callback function or method that is called when the button is clicked. The gtk.Button class has the following constructor − gtk.Button(label = None, stock = None, use_underline = True) Wherein, Label − The text to be displayed by the button label Stock − The stock id identifying the stock image and text to be used in the button. Default is None. Underline − If True, an underscore in the text indicates the next character should be underlined and used for the mnemonic accelerator. Some of the predefined constants for stock parameter are − STOCK_OK STOCK_STOP STOCK_YES STOCK_NO STOCK_QUIT STOCK_CANCEL STOCK_CLOSE The Button class has the following important methods − S.NO Methods and Description 1 set_label() This sets the text of the button label to label. This string is also used to select the stock item if the “use_stock” property is True. 2 get_label() This retrieves the text from the label of the button 3 set_focus_on_click() If True, the button grabs focus when clicked with the mouse. 4 set_alignment() This is the horizontal and vertical alignment of the child widget. The value ranges from 0.0 to 1.0. 5 set_image() This sets the image property to the value of image. The “gtkbutton-images” property should be set to True. The following signals are emitted by the Button widget − activate This is emitted when the gtk.Widget”s activate() method is called. For a button it causes the “clicked” signal to be emitted. clicked This is emitted when the mouse button is pressed and released while the pointer is over the button or when the button is triggered with the keyboard. Print Page Previous Next Advertisements ”;

PyGTK – Image Class

PyGTK – Image Class ”; Previous Next This class is also inherited from the gtk.Misc class. The object of the gtk.Image class displays an image. Usually, the image is to be loaded from a file in a pixel buffer representing gtk.gdk.Pixbuf class. Instead a convenience function set_from_file() is commonly used to display image data from file in a gk.Image widget. The easiest way to create the gtk.Image object is to use the following constructor − img = gtk.Image() The following are the methods of the gtk.Image class − Image.set_from_file() − This sets the image data from the contents of the file. Image.set_from_pixbuf() − This sets the image data from pixmap in which the image data is loaded for offscreen manipulation. Image.set_from_pixbuf() − This sets the image data using pixbuf which is an object containing the data that describes an image using client side resources. Image.set_from_stock() − This sets the image data from the stock item identified by stock_id. Image.clear() − This removes the current image. Image.set_from_image() − This sets the image data from a client-side image buffer in the pixel format of the current display. If the image is None, the current image data will be removed. Example In the following program, the gtk.Image object is obtained from an image file. It is further added in the toplevel window. import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“PyGtk Image demo”) self.set_size_request(300, 200) self.set_position(gtk.WIN_POS_CENTER) image1 = gtk.Image() image1.set_from_file(“python.png”) self.add(image1) self.connect(“destroy”, gtk.main_quit) self.show_all() PyApp() gtk.main() The above code will generate the following output − Print Page Previous Next Advertisements ”;

PyGTK – Timeout

PyGTK – Timeout ”; Previous Next The gobject module of the PyGTK API has a useful function to create a timeout function that will be called periodically. source_id = gobject.timeout_add(interval, function, …) The second argument is the callback function you wish to have called after every millisecond which is the value of the first argument – interval. Additional arguments may be passed to the callback as function data. The return value of this function is source_id. Using it, the callback function is stopped from calling. gobject.source_remove(source_id) The callback function must return True in order to keep repeating. Therefore, it can be stopped by returning False. Two buttons and two labels are put on a toplevel window in the following program. One label displays an incrementing number. The btn1 calls on_click which sets the timeout function with an interval of 1000 ms (1 second). btn1.connect(“clicked”, self.on_click) def on_click(self, widget): self.source_id = gobject.timeout_add(1000, counter, self) The timeout function is named as counter(). It increments the number on a label after every 1 second. def counter(timer): c=timer.count+1 print c timer.count=c timer.lbl.set_label(str(c)) return True The Callback on the second button removes the timeout function. btn2.connect(“clicked”, self.on_stop) def on_stop(self, widget): gobject.source_remove(self.source_id) Example The following is the complete code for the Timeout example − import gtk, gobject def counter(timer): c = timer.count+1 print c timer.count = c timer.lbl.set_label(str(c)) return True class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“Timeout Demo”) self.set_size_request(300, 200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox(False, 5) hbox = gtk.HBox(True, 3) hb = gtk.HBox() lbl1 = gtk.Label(“Counter: “) hb.add(lbl1) self.lbl = gtk.Label(“”) hb.add(self.lbl) valign = gtk.Alignment(0.5, 0.5, 0, 0) valign.add(hb) vbox.pack_start(valign, True, True, 10) btn1 = gtk.Button(“start”) btn2 = gtk.Button(“stop”) self.count = 0 self.source_id = 0 hbox.add(btn1) hbox.add(btn2) halign = gtk.Alignment(0.5, 0.5, 0, 0) halign.add(hbox) vbox.pack_start(halign, False, True, 10) self.add(vbox) btn1.connect(“clicked”, self.on_click) btn2.connect(“clicked”, self.on_stop) self.connect(“destroy”, gtk.main_quit) self.show_all() def on_click(self, widget): self.source_id = gobject.timeout_add(1000, counter, self) def on_stop(self, widget): gobject.source_remove(self.source_id) PyApp() gtk.main() When executed, the window shows two buttons at the bottom. The number on the label will increment periodically when the Start button is clicked on and it will stop incrementing when the Stop button is clicked on. Observe the output − Print Page Previous Next Advertisements ”;