PyGTK – Frame Class ”; Previous Next Frame class is a subclass of the gtk.Bin class. It draws a decorative border around the child widget placed in it. The frame may contain a label whose position may be customized. A gtk.Frame object is constructed with the help of the following constructor − frame = gtk.Frame(label = None) The following are the methods of the gtk.Frame() class − set_label(text) − This sets the label as specified by text. If None, the current label is removed. set_label_widget() − This sets a widget other than gtk.Label as label for frame. set_label_align(x, y) − This sets the alignment of the frame”s label widget and decoration (defaults are 0.0 and 0.5) set_shadow_type() − This sets the frame”s shadow type. The possible values are − gtk.SHADOW_NONE gtk.SHADOW_IN gtk.SHADOW_OUT gtk.SHADOW_ETCHED_IN tk.SHADOW_ETCHED_OUT The following code demonstrates the functioning of the Frame widget. A group of three objects of gtk.RadioButton is placed in an HButtonBox. btn1 = gtk.RadioButton(None,”Degree”) btn2 = gtk.RadioButton(btn1,”P.G.”) btn3 = gtk.RadioButton(btn1,”Doctorate”) hb = gtk.HButtonBox() hb.add(btn1) hb.add(btn2) hb.add(btn3) In order to draw border around the box, it is placed in a Frame widget, and it is added to the toplevel window. frm = gtk.Frame() frm.add(hb) self.add(frm) Example Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“Frame Demo”) self.set_default_size(250, 200) self.set_border_width(5) frm = gtk.Frame() hb = gtk.HButtonBox() btn1 = gtk.RadioButton(None,”Degree”) hb.add(btn1) btn2 = gtk.RadioButton(btn1,”P.G.”) hb.add(btn2) btn3 = gtk.RadioButton(btn1,”Doctorate”) hb.add(btn3) frm.add(hb) frm.set_label(“Qualifications”) self.add(frm) self.connect(“destroy”, gtk.main_quit) self.show_all() if __name__ == ”__main__”: PyApp() gtk.main() The above code will generate the following output − Print Page Previous Next Advertisements ”;
Category: pygtk
PyGTK – DrawingArea Class
PyGTK – DrawingArea Class ”; Previous Next The DrawingArea widget presents a blank canvas containing a gtk.gdk.Window on which objects such as line, rectangle, arc, etc. can be drawn. PyGTK uses Cairo library for such drawing operations. Cairo is a popular 2D vector graphics library. It is written in C., although, it has bindings in most Languages such as C++, Java, Python, PHP etc. Cairo library can be used to draw on standard output devices in various operating systems. It can also be used to create PDF, SVG and post-script files. In order to perform different drawing operations, we must fetch the device on text of the target output object. In this case, since the drawing is appearing on gtk.DrawingArea widget, the device context of gdk.Window contained inside it is obtained. This class has a cairo-create() method which returns the device context. area = gtk.DrawingArea() dc = area.window.cairo_create() The DrawingArea widget can be connected to the callbacks based on the following signals emitted by it − Realize To take any necessary actions when the widget is instantiated on a particular display. configure_event To take any necessary actions when the widget changes size. expose_event To handle redrawing the contents of the widget when a drawing area first comes on screen, or when it”s covered by another window and then uncovered (exposed). The Mouse and Keyboard events can also be used to invoke callbacks by add_events() method of the gtk.Widget class. Of particular interest is the expose-event signal which is emitted when the DrawingArea canvas first comes up. The different methods for drawing 2D objects, that are defined in the Cairo library are called from this callback connected to the expose-event signal. These methods draw corresponding objects on the Cairo device context. The following are the available drawing methods − dc.rectangle(x,y,w,h) − This draws a rectangle at the specified top left coordinate and having givwn width and height. dc.arc(x,y,r,a1,a2) − This draws a circular arc with given radius and two angles. dc.line(x1, y1, x2, y2) − This draws a line between two pairs of coordinates. dc.line_to(x,y) − This draws a line from the current position to (x,y) dc.show_text(str) − draws string at current cursor position dc.stroke() − draws outline dc.fill() − fills shape with current color dc.set_color_rgb(r,g,b) − sets color to outline and fill with r, g and b values between 0.0 to 1.0 Example The following script draws different shapes and test using Cairo methods. import gtk import math class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“Basic shapes using Cairo”) self.set_size_request(400, 250) self.set_position(gtk.WIN_POS_CENTER) self.connect(“destroy”, gtk.main_quit) darea = gtk.DrawingArea() darea.connect(“expose-event”, self.expose) self.add(darea) self.show_all() def expose(self, widget, event): cr = widget.window.cairo_create() cr.set_line_width(2) cr.set_source_rgb(0,0,1) cr.rectangle(10,10,100,100) cr.stroke() cr.set_source_rgb(1,0,0) cr.rectangle(10,125,100,100) cr.stroke() cr.set_source_rgb(0,1,0) cr.rectangle(125,10,100,100) cr.fill() cr.set_source_rgb(0.5,0.6,0.7) cr.rectangle(125,125,100,100) cr.fill() cr.arc(300, 50, 50,0, 2*math.pi) cr.set_source_rgb(0.2,0.2,0.2) cr.fill() cr.arc(300, 200, 50, math.pi,0) cr.set_source_rgb(0.1,0.1,0.1) cr.stroke() cr.move_to(50,240) cr.show_text(“Hello PyGTK”) cr.move_to(150,240) cr.line_to(400,240) cr.stroke() PyApp() gtk.main() The above script will generate the following output − Print Page Previous Next Advertisements ”;
PyGTK – Font Selection Dialog ”; Previous Next The gtk.FontSelection widget allows users to select and apply the font of a particular name, size and style. The dialog has a preview box containing some text which will be displayed in selected font description, and two buttons CANCEL and OK. PyGTK API contains a Pango module which defines classes and functionality required to render high quality internationalized text. Font and text handling in gtk is supported by Pango. The pango.Font object represents a font in a system independent way. The pango.FontDescription object contains the characteristics of a font. gtk.FontSelectionDialog returns a pango.Font object. In order to apply the selected font, fontmetrics is fetched by obtaining the pango.FontDescription object from it. The following is a constructor of the FontSelectionDialog class − dlg = gtk.FontSelectionDialog(title) The following are some frequently used methods of this class − get_font_name() − This returns a string containing the currently selected font name or None if no font name is selected. set_font_name() − This sets the current font set_preview_text() − This sets the text in the preview area entry The selected font is applied to the text in a widget using the modify_font() method. When FontSelectionDialog menu item is activated, the following callback function is invoked − def on_abtdlg(self, widget): about = gtk.AboutDialog() about.set_program_name(“PyGTK Dialog”) about.set_version(“0.1”) about.set_authors(“M.V.Lathkar”) about.set_copyright(“(c) TutorialsPoint”) about.set_comments(“About Dialog example”) about.set_website(“http://www.tutorialspoint.com”) about.run() about.destroy() The selected font is applied to the text of label placed on the toplevel window. The following is the output − Print Page Previous Next Advertisements ”;
PyGTK – Scale Class
PyGTK – Scale Class ”; Previous Next This class acts as an abstract base class for HScale and VScale widgets. These widgets work as a slider control and select a numeric value. The following methods of this abstract class are implemented by the HScale class and the VScale class − set_digits() − This sets number of decimal places to be used to display instantaneous value of widget. set_draw_value() − set to True, current value will be displayed next to the slider. set_value_pos() − This is the position at which the values are drawn. This can be either gtk.POS_LEFT, gtk.POS_RIGHT, gtk.POS_TOP or gtk.POS_BOTTOM. An object of gtk.HScale class provides a horizontal slider, whereas an object of gtk.VScale class provides vertical slider. Both classes have identical constructors − gtk.HScale(Adjustment = None) gtk.VScale(Adjustment = None) The adjustment object contains many attributes that provide access to value and bounds. Print Page Previous Next Advertisements ”;
PyGTK – EventBox Class
PyGTK – EventBox Class ”; Previous Next Some widgets in PyGTK tool kit do not have their own window. Such windowless widgets cannot receive event signals. Such widgets, for example a label, if put inside an eventbox can receive signals. EventBox is an invisible container that provides window to windowless widgets. It has a simple constructor without any argument − gtk.EventBox() Example In the following example, two widgets of the gtk.EventBox are placed in the toplevel window. Inside each eventbox, a label is added. The eventbox is now connected to a callback function to process the button_press_event on it. As the eventbox itself is invisible, effectively the event occurs on the embedded label. Hence, as and when we click on any label, the corresponding callback function is invoked. Observe the code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“EventBox demo”) self.set_size_request(200,100) self.set_position(gtk.WIN_POS_CENTER) fixed = gtk.Fixed() event1 = gtk.EventBox() label1 = gtk.Label(“Label 1”) event1.add(label1) fixed.put(event1, 80,20) event1.connect(“button_press_event”,self.hello1) event2 = gtk.EventBox() label2 = gtk.Label(“Label 2”) event2.add(label2) event2.connect(“button_press_event”,self.hello2) fixed.put(event2, 80,70) self.add(fixed) self.connect(“destroy”, gtk.main_quit) self.show_all() def hello1(self, widget, event): print “clicked label 1” def hello2(self, widget, event): print “clicked label 2″ PyApp() gtk.main() The above code generates the following output − When Label 1 is clicked on the console, the message “clicked label 1” gets printed. Similarly, when Label 2 is clicked on, “clicked label 2” message is printed. Print Page Previous Next Advertisements ”;
PyGTK – Adjustment Class
PyGTK – Adjustment Class ”; Previous Next Some widgets in PyGTK toolkit are such that their properties can be adjusted over a specified range by the user by using a mouse or a keyboard. A widget like Viewport is used to display some adjustable portion of a large data, for example, a multiline text in TextView control. PyGTK uses gtk.Adjustment object to be used in association with such widgets so that user adjustments are passed to some callback function for processing. An Adjustment object contains lower and upper bounds of an adjustable value and its increment step paramaters. When parameters of adjustment object changes, it emits changed or value_changed signals. The following is the constructor of the gtk.Adjustment class − gtk.Adjustment(value = 0, lower = 0, upper = 0, step_incr = 0, page_incr = 0, page_size = 0) The meaning of each of the attributes in the constructor is as follows − value The initial value lower The minimum value upper The maximum value step_incr The step increment page_incr The page increment page_size The page sizes The following signals are emitted by the Adjustment object − Changed This is emitted when one (or more) of the adjustment attributes (except the value attribute) has changed. Value-changed This is emitted when the adjustment value attribute has changed. As mentioned above, the Adjustment object is not a physical widget. Rather, it is used in association with the other widgets using which its attributes get changed. Range widgets are used along with the Adjustment object. Print Page Previous Next Advertisements ”;
PyGTK – TreeView Class
PyGTK – TreeView Class ”; Previous Next The Treeview widget displays contents of a model implementing the gtk.TreeModel interface. PyGTK provides the following types of models − gtk.ListStore gtk.TreeStore gtk.TreeModelSort ListStore is a list model. When associated with a gtk.TreeView widget, it produces a List box containing the items to be selected from. A gtk.ListStore object is declared with following syntax − store = gtk.ListStore(column_type) A list may have multiple columns, the predefined type constants are − gobject.TYPE_BOOLEAN gobject.TYPE_BOXED gobject.TYPE_CHAR gobject.TYPE_DOUBLE gobject.TYPE_ENUM gobject.TYPE_FLOAT gobject.TYPE_INT gobject.TYPE_LONG gobject.TYPE_NONE gobject.TYPE_OBJECT gobject.TYPE_STRING gobject.TYPE_UCHAR gobject.TYPE_UINT gobject.TYPE_ULONG gtk.gdk.pixbuf etc. For example, a ListStore object to store string items is declared as − store = gtk.ListStore(gobject.TYPE_STRING In order to add items in the store, append() methods are used − store.append ([“item 1″]) TreeStore is a model for multi-columned Tree widget. For example, the following statement creates a store with one column having string item. Store = gtk.TreeStore(gobject.TYPE_STRING) In order to add items in a TreeStore, use the append() method. The append() method has two parameters, parent and row. To add toplevel item, parent is None. row1 = store.append(None, [”row1”]) You need to repeat this statement to add multiple rows. In order to add child rows, pass the toplevel row as parent parameter to the append() method − childrow = store.append(row1, [”child1”]) You need to repeat this statement to add multiple child rows. Now, create a TreeView widget and use the above TreeStore object as model. treeview = gtk.TreeView(store) We now have to create TreeViewColumn to display store data. The object of gtk.TreeViewColumn manages header and the cells using gtk.CelRenderer. TreeViewColumn object is created using the following constructor − gtk.TreeViewColumn(title, cell_renderer,…) In addition to title and renderer, it takes zero or more attribute=column pairs to specify from which tree model column the attribute”s value is to be retrieved. These parameters can also be set using methods of TreeViewColumn class given below. A gtk.CellRenderer is a base class for a set of objects for rendering different types of data. The derived classes are CellRendererText, CellRendererPixBuf and CellRendererToggle. The following methods of the TreeViewColumn class are used to configure its object − TreeViewColumn.pack_start(cell, expand = True) − This method packs the CellRenderer object into the beginning column. If expand parameter is set to True, columns entire allocated space is assigned to cell. TreeViewColumn.add_attribute(cell, attribute, column) − This method adds an attribute mapping to the list in the tree column. The column is the column of the tree model. TreeViewColumn.set_attributes() − This method sets the attribute locations of the renderer using the attribute = column pairs TreeViewColumn.set_visible() − If True, the treeview column is visible TreeViewColumn.set_title() − This method sets the “title” property to the value specified. TreeViewColumn.set_lickable() − If set to True, the header can take keyboard focus, and be clicked. TreeViewColumn.set_alignment(xalign) − This method sets the “alignment” property to the value of xalign. The “clicked” signal is emitted when the user clicks on the treeviewcolumn header button. After having configured the TreeViewColumn object, it is added to the TreeView widget using the append_column() method. The following are the important methods of the TreeView class − TreevVew.set_model() − This sets the “model” property for the treeview. If the treeview already has a model set, this method will remove it before setting the new model. If model is None, it will unset the old model. TreeView.set_header_clickable() − If set to True, the column title buttons can be clicked. TreeView.append_column() − This appends the specified TreeViewColumn to the list of columns. TreeView.remove_column() − This removes the specified column from the treeview. TreeView.insert_column() − This inserts the specified column into the treeview at the location specified by position. The TreeView widget emits the following signals − cursor-changed This is emitted when the cursor moves or is set. expand-collapse-cursor-row This is emitted when the row at the cursor needs to be expanded or collapsed. row-activated This is emitted when the user double clicks a treeview row row-collapsed This is emitted when a row is collapsed by the user or programmatic action. row-expanded This is emitted when a row is expanded via the user or programmatic action. Two examples of the TreeView widget are given below. The first example uses a ListStore to produce a simple ListView. Here a ListStore object is created and string items are added to it. This ListStore object is used as model for TreeView object − store = gtk.ListStore(str) treeView = gtk.TreeView() treeView.set_model(store) Then a CellRendererText is added to a TreeViewColumn object and the same is appended to TreeView. rendererText = gtk.CellRendererText() column = gtk.TreeViewColumn(“Name”, rendererText, text = 0) treeView.append_column(column) TreeView Object is placed on the toplevel window by adding it to a Fixed container. Example 1 Observe the following code − import pygtk pygtk.require(”2.0”) import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“TreeView with ListStore”) self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) store = gtk.ListStore(str) store.append ([“PyQt”]) store.append ([“Tkinter”]) store.append ([“WxPython”]) store.append ([“PyGTK”]) store.append ([“PySide”]) treeView = gtk.TreeView() treeView.set_model(store) rendererText = gtk.CellRendererText() column = gtk.TreeViewColumn(“Python GUI Libraries”, rendererText, text=0) treeView.append_column(column) fixed = gtk.Fixed() lbl = gtk.Label(“select a GUI toolkit”) fixed.put(lbl, 25,75) fixed.put(treeView, 125,15) lbl2 = gtk.Label(“Your choice is:”) fixed.put(lbl2, 25,175) self.label = gtk.Label(“”) fixed.put(self.label, 125,175) self.add(fixed) treeView.connect(“row-activated”, self.on_activated) self.connect(“destroy”, gtk.main_quit) self.show_all() def on_activated(self, widget, row, col): model = widget.get_model() text = model[row][0] self.label.set_text(text) def main(): gtk.main() return if __name__ == “__main__”: bcb = PyApp() main() The item selected by the user is displayed on a label in the window as the on_activated callback function is invoked. Example 2 The second example builds a hierarchical TreeView from a TreeStore. This program follows the same sequence of building the store, setting it as model for TreeView, designing a TreeViewColumn and appending it to TreeView. import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“TreeView with TreeStore”) self.set_size_request(400,200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox(False, 5) # create a TreeStore with one string column to use as the model store = gtk.TreeStore(str) # add row row1 = store.append(None, [”JAVA”]) #add child rows store.append(row1,[”AWT”]) store.append(row1,[”Swing”]) store.append(row1,[”JSF”]) # add another row row2 = store.append(None, [”Python”]) store.append(row2,[”PyQt”]) store.append(row2,[”WxPython”]) store.append(row2,[”PyGTK”])
PyGTK – Range Class
PyGTK – Range Class ”; Previous Next This class acts as a base class for widgets which let the user to adjust the value of a numeric parameter between the lower and upper bounds. Scale widgets (gtk.Hscale and gtk.Vscale) and scrollbar widgets (gtk.HScrollbar and gtk.VScrollbar) derive functionality from the Range class. These Range widgets work in conjunction with the Adjustment object. The following important functions of the gtk.Range class are implemented by the Scale and Scrollbar widgets − set_update_policy() − This sets the “update-policy” property to the value. The policy has the following values − gtk.UPDATE_CONTINUOUS anytime the range slider is moved, the range value will change and the “value_changed” signal will be emitted. gtk.UPDATE_DELAYED the value will be updated after a brief timeout where no slider motion occurs, so value changes are delayed slightly rather than continuously updated. gtk.UPDATE_DISCONTINUOUS the value will only be updated when the user releases the button and ends the slider drag operation. set_adjustment() − This sets the “adjustment” property. The Adjustment object is used as model for the Range object. set_increments() − This sets the step and page sizes for the range. set_range() − This sets the minimum and maximum allowable values for the Range widget set_value() − This sets the current value of the range to the value specified. The scale widget classes − (HScale and VScale) are derived from the gtk.Range class. Print Page Previous Next Advertisements ”;
PyGTK – Paned Class
PyGTK – Paned Class ”; Previous Next Paned class is the base class for widgets which can display two adjustable panes either horizontally (gtk.Hpaned) or vertically (gtk.Vpaned). Child widgets to panes are added by using pack1() and pack2() methods. Paned widget draws a separator slider between two panes and provides a handle to adjust their relative width/height. If the resize property of child widget inside a pane is set to True, it will resize according to the size of the panes. The following methods are available for HPaned as well as VPaned class − Paned.add1(child) − This adds the widget specified by child to the top or left pane Paned.add2(child) − This adds the widget specified by child to the bottom or right pane. Paned.pack1(child, resize, shrink) − This adds the widget specified by child to the top or left pane with the parameters. If resize is True, child should be resized when the paned widget is resized. If shrink is True, child can be made smaller than its minimum size request. Paned.pack2(child, resize, shrink) − This sets the position of the divider between the two panes. Both types of Paned widgets emit the following signals − accept-position This is emitted when paned has the focus causing the child widget with the focus to be activated. cancel-position This is emitted when the Esc key is pressed while paned has the focus. move-handle This is emitted when paned has the focus and the separator is moved. Example The following example uses a gtk.Hpaned widget. In the left pane, a TreeView widget is added, and in the right pane, there is a TextView widget. When any row in TreeView is selected, it will emit row_activated signal which is connected to a callback function. The on_activated()function retrieves row”s text and displays in the text view panel. Observe the code − import gtk, gobject class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“HPaned widget Demo”) self.set_default_size(250, 200) vp = gtk.HPaned() sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) tree = gtk.TreeView() languages = gtk.TreeViewColumn() languages.set_title(“GUI Toolkits”) cell = gtk.CellRendererText() languages.pack_start(cell, True) languages.add_attribute(cell, “text”, 0) treestore = gtk.TreeStore(str) it = treestore.append(None, [“Python”]) treestore.append(it, [“PyQt”]) treestore.append(it, [“wxPython”]) treestore.append(it, [“PyGTK”]) treestore.append(it, [“Pydide”]) it = treestore.append(None, [“Java”]) treestore.append(it, [“AWT”]) treestore.append(it, [“Swing”]) treestore.append(it, [“JSF”]) treestore.append(it, [“SWT”]) tree.append_column(languages) tree.set_model(treestore) vp.add1(tree) self.tv = gtk.TextView() vp.add2(self.tv) vp.set_position(100) self.add(vp) tree.connect(“row-activated”, self.on_activated) self.connect(“destroy”, gtk.main_quit) self.show_all() def on_activated(self, widget, row, col): model = widget.get_model() text = model[row][0] print text buffer = gtk.TextBuffer() buffer.set_text(text+” is selected”) self.tv.set_buffer(buffer) if __name__ == ”__main__”: PyApp() gtk.main() The above code will generate the following output − Print Page Previous Next Advertisements ”;
PyGTK – Statusbar Class
PyGTK – Statusbar Class ”; Previous Next A notification area, usually at the bottom of a window is called the status bar. Any type of status change message can be displayed on the status bar. It also has a grip using which it can be resized. The gtk.Statusbar widget maintains a stack of messages. Hence, new message gets displayed on top of the current message. If it is popped, earlier message will be visible again. Source of the message must be identified by context_id to identify it uniquely. The following is the constructor of the gtk.Statusbar widget − bar = gtk.Statusbar() The following are the methods of the gtk.Statusbar class − Statusbar.push(context_id, text) − This pushes a new message onto a statusbar”s stack. Statusbar.pop(context_id) − This removes the top message with the specified context_id from the statusbar”s stack. The following signals are emitted by the Statusbar widget − text-popped This is emitted when a message is removed from the statusbar message stack. text-pushed This is emitted when a message is added to the statusbar message stack. The following example demonstrates the functioning of Statusbar. Toplevel window contains a VBox with two rows. Upper row has a Fixed widget in which a label, an Entry widget and a button is put. Whereas, in the bottom row, a gtk.Statusbar widget is added. In order to send message to status bar, its context_id needs to be fetched. id1 = self.bar.get_context_id(“Statusbar”) The ”clicked” signal of the Button object is connected to a callback function through which a message is pushed in the status bar. And, the ”activate” signal is emitted when Enter key is pressed inside the Entry widget. This widget is connected to another callback. btn.connect(“clicked”, self.on_clicked, id1) txt.connect(“activate”, self.on_entered, id1) Both callbacks use push() method to flash the message in the notification area. Example Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“Statusbar demo”) self.set_size_request(400,200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox() fix = gtk.Fixed() lbl = gtk.Label(“Enter name”) fix.put(lbl, 175, 50) txt = gtk.Entry() fix.put(txt, 150, 100) btn = gtk.Button(“ok”) fix.put(btn, 200,150) vbox.add(fix) self.bar = gtk.Statusbar() vbox.pack_start(self.bar, True, False, 0) id1 = self.bar.get_context_id(“Statusbar”) btn.connect(“clicked”, self.on_clicked, id1) txt.connect(“activate”, self.on_entered, id1) self.add(vbox) self.connect(“destroy”, gtk.main_quit) self.show_all() def on_clicked(self, widget, data=None): self.bar.push(data, “Button clicked def on_entered(self, widget, data): self.bar.push(data, “text entered”) PyApp() gtk.main() Upon execution, the above code will display the following output − Try typing in the text box and press Enter to see the ”text entered” message in status bar. Print Page Previous Next Advertisements ”;