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”])
Category: 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 – CheckButton Class
PyGTK – CheckButton Class ”; Previous Next A CheckButton widget is nothing but a ToggleButton styled as a checkbox and a label. It inherits all properties and methods from the ToggleButton class. Unlike ToggleButton where the caption is on the button”s face, a CheckButton displays a small square which is checkable and has a label to its right. Constructor, methods, and signals associated with gtk.CheckButton are exactly the same as gtk.ToggleButton. Example The following example demonstrates the use of CheckButton widget. Two CheckButtons and a Label are placed in a VBox. The toggled signal of the first CheckButton is connected to the on_checked() method which sets the state of the second button to True if that of the first is false and vice versa. Observe the code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“Check Button”) self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox() self.btn1 = gtk.CheckButton(“Button 1”) self.btn1.connect(“toggled”, self.on_checked) self.btn2 = gtk.CheckButton(“Button 2”) self.btn2.connect(“toggled”, self.on_checked) self.lbl = gtk.Label() vbox.add(self.btn1) vbox.add(self.btn2) vbox.add(self.lbl) self.add(vbox) self.connect(“destroy”, gtk.main_quit) self.show_all() def on_checked(self, widget, data = None): state = “Button1 : “+str(self.btn1.get_active())+” Button2 : “+str(self.btn2.get_active()) self.lbl.set_text(state) if __name__ == ”__main__”: PyApp() gtk.main() The above code will generate the following output − Print Page Previous Next Advertisements ”;
PyGTK – Box Class
PyGTK – Box Class ”; Previous Next The gtk.Box class is an abstract class defining the functionality of a container in which widgets are placed in a rectangular area. gtk.HBox and gtk.VBox widgets are derived from it. Child widgets in gtk.Hbox are arranged horizontally in the same row. On the other hand, child widgets of gtk.VBox are arranged vertically in the same column. gtk.Box class uses the following constructor − gtk.Box(homogenous = True, spacing = 0) The homogenous property is set to True by default. As a result, all child widgets are given equal allocation. gtk.Box uses the packing mechanism to place child widgets in it with reference to a particular position, either with reference to start or end. pack_start() method places widgets from start to end. On the contrary, the pack_end() method puts widgets from end to start. Alternatively, you can use the add() method which is similar to pack_start(). The following methods are available for gtk.HBox as well as gtk.VBox − gtk_box_pack_start () gtk_box_pack_end () gtk_box_pack_start () This method adds child to the box, packed with reference to the start of box − pack_start(child, expand = True, fill = True, padding = 0) The following are the parameters − child − This is the widget object to be added to box expand − This is set to True if child is to be given extra space in the box. Extra space is divided between all child widgets. fill − If True, extra space will be allocated to child. Otherwise, this parameter is used as padding. padding − This is the space in pixels between widgets in the box. gtk_box_pack_end () This adds child to the box, packed with reference to the end of the box. pack_end (child, expand = True, fill = True, padding = 0) The following are the parameters − child − This is the widget object to be added expand − This is set to True if child is to be given extra space in the box. This extra space is divided between all child widgets. fill − If True, extra space will be allocated to child otherwise used as padding. padding − This is the space in pixels between the widgets in the box. set_spacing (spacing) is the function that sets the number of pixels to place between the children of the box. The method add (widget) is inherited from the gtk.Container class. It adds widget to the container. This method can be used instead of the pack_start() method. Example In the example given below, the toplevel window contains a vertical box (gtk.VBox object box). It in turn has a VBox object vb and HBox object hb. In the upper box, a label, an entry widget and a button are placed vertically. In the lower box, another set of label, entry and button are placed vertically. Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“Box demo”) box = gtk.VBox() vb = gtk.VBox() lbl = gtk.Label(“Enter name”) vb.pack_start(lbl, expand = True, fill = True, padding = 10) text = gtk.Entry() vb.pack_start(text, expand = True, fill = True, padding = 10) btn = gtk.Button(stock = gtk.STOCK_OK) vb.pack_start(btn, expand = True, fill = True, padding = 10) hb = gtk.HBox() lbl1 = gtk.Label(“Enter marks”) hb.pack_start(lbl1, expand = True, fill = True, padding = 5) text1 = gtk.Entry() hb.pack_start(text1, expand = True, fill = True, padding = 5) btn1 = gtk.Button(stock = gtk.STOCK_SAVE) hb.pack_start(btn1, expand = True, fill = True, padding = 5) box.add(vb) box.add(hb) self.add(box) self.show_all() PyApp() gtk.main() The above code will produce the following output − Print Page Previous Next Advertisements ”;
PyGTK – Event Handling
PyGTK – Event Handling ”; Previous Next In addition to the signal mechanism, window system events can also be connected to callback functions. Window resizing, key press, scroll event etc. are some of common window system events. These events are reported to application”s main loop. From there, they are passed along via signals to the callback functions. Some of the system events are listed below − button_press_event button_release_event scroll_event motion_notify_event delete_event destroy_event expose_event key_press_event key_release_event The connect() method is used to associate the event with callback function following the syntax − Object.connect(name, function, data) Here, name stands for the string corresponding to the name of event which is to be captured. And, function is name of the callback function that is to be called when an event occurs. Data is the argument to be passed on to the callback function. Hence, the following code connects a Button widget and captures the button_press event − self.btn.connect(“button_press_event”, self.hello) The following will be the Prototype of hello() function − def hello(self,widget,event): Example The following is the code for button event handler − 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(“button_press_event”, 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,event): print “hello”,self.entry.get_text() PyApp() gtk.main() When you run the above code, it displays the following output on the console − Hello TutorialsPoint Print Page Previous Next Advertisements ”;
PyGTK – RadioButton Class
PyGTK – RadioButton Class ”; Previous Next A single RadioButton widget offers functionality similar to CheckButton. However, when more than one radio button is present in the same container, then a mutually exclusive choice is available for the user to choose from one of the available options. If every radio button in the container belongs to the same group, then as one is selected, others are automatically deselected. The following is a constructor of the gtk.RadioButton class − gtk.RadioButton(group = None, Label = None, unerline = None) In order to create a button group, provide group=None for the first Radio button, and for the subsequent options, provide the object of the first button as group. As in case of ToggleButton and CheckButton, the RadioButton also emits the toggled signal. In the example given below, three objects of the gtk.RadioButton widget are placed in a VBox. All of them are connected to a callback function on_selected(), to process the toggled signal. The callback function identifies the label of source RadioButton widget and displays it on the label put in the VBox. Example Observe the following code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“Radio Button”) self.set_default_size(250, 200) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox() btn1 = gtk.RadioButton(None, “Button 1”) btn1.connect(“toggled”, self.on_selected) btn2 = gtk.RadioButton(btn1,”Button 2″) btn2.connect(“toggled”, self.on_selected) btn3 = gtk.RadioButton(btn1,”Button 3″) btn3.connect(“toggled”, self.on_selected) self.lbl = gtk.Label() vbox.add(btn1) vbox.add(btn2) vbox.add(btn3) vbox.add(self.lbl) self.add(vbox) self.connect(“destroy”, gtk.main_quit) self.show_all() def on_selected(self, widget, data=None): self.lbl.set_text(widget.get_label()+” is selected”) if __name__ == ”__main__”: PyApp() gtk.main() The above code will generate the following output − Print Page Previous Next Advertisements ”;
PyGTK – Containers
PyGTK – Containers ”; Previous Next PyGTK library provides different container classes to control the placement of widgets inside a window. The easiest way is to use a fixed container class and place a widget inside it by specifying its absolute coordinates measured in pixels. Let us now follow these steps − Step 1 − Declare an object of the fixed class fixed = gtk.Fixed() Step 2 − Create a button widget and add it to the fixed container by using put() method which needs x and y coordinates. Here, the button will be placed at (100,100) position. btn = gtk.Button(“Hello”) fixed.put(btn, 100,100) Step 3 − You can place multiple controls in the fixed container. And, add it to the top-level window and invoke the show_all() method self.add(fixed) self.show_all() This Absolute Layout, however, is not suitable because of the following reasons − The position of the widget does not change even if the window is resized. The appearance may not be uniform on different display devices with different resolutions. Modification in the layout is difficult as it may need redesigning of the entire form. The following is the original window − The following is the resized window − The position of the button is unchanged here. PyGTK API provides container classes for enhanced management of positioning of widgets inside the container. The advantages of Layout managers over absolute positioning are − Widgets inside the window are automatically resized. Ensures uniform appearance on display devices with different resolutions. Adding or removing widget dynamically is possible without having to redesign. gtk.Container acts as the base class for the following classes − gtk.ButtonBox gtk.Box gtk.Alignment gtk.EventBox gtk.Table Print Page Previous Next Advertisements ”;
PyGTK – ButtonBox Class
PyGTK – ButtonBox Class ”; Previous Next The ButtonBox class in gtk API serves as a base class for containers to hold multiple buttons either horizontally or vertically. Two subclasses HButtonBox and VButtonBox are derived from the ButtonBox class, which itself is a subclass of gtk.Box class. A button box is used to provide a consistent layout of buttons throughout an application. It provides one default layout and a default spacing value that are persistent across all widgets. The set_spacing() method of the gtk.Box class can be used to change the default spacing between buttons in the button box. The default layout of buttons can be changed by the set_default() method. The possible values of the button layout are − gtk.BUTTONBOX_SPREAD gtk.BUTTONBOX_EDGE gtk.BUTTONBOX_START gtk.BUTTONBOX_END. Example In the following example, a VBox object inside the toplevel window internally contains one VButtonBox object and one HButtonBox object, each containing two buttons, arranged vertically and horizontally respectively. Observe the code − import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title(“Button Box demo”) self.set_size_request(200,100) self.set_position(gtk.WIN_POS_CENTER) vb = gtk.VBox() box1 = gtk.VButtonBox() btn1 = gtk.Button(stock = gtk.STOCK_OK) btn2 = gtk.Button(stock = gtk.STOCK_CANCEL) box1.pack_start(btn1, True, True, 0) box1.pack_start(btn2, True, True, 0) box1.set_border_width(5) vb.add(box1) box2 = gtk.HButtonBox() btn3 = gtk.Button(stock = gtk.STOCK_OK) btn4 = gtk.Button(stock = gtk.STOCK_CANCEL) ent = gtk.Entry() box2.pack_start(btn3, True, True, 0) box2.pack_start(btn4, True, True, 0) box1.set_border_width(5) vb.add(box2) self.add(vb) self.show_all() PyApp() gtk.main() The above code generates the following output − Print Page Previous Next Advertisements ”;
PyGTK – Hello World
PyGTK – Hello World ”; Previous Next Creating a window using PyGTK is very simple. To proceed, we first need to import the gtk module in our code. import gtk The gtk module contains the gtk.Window class. Its object constructs a toplevel window. We derive a class from gtk.Window. class PyApp(gtk.Window): Define the constructor and call the show_all() method of the gtk.window class. def __init__(self): super(PyApp, self).__init__() self.show_all() We now have to declare the object of this class and start an event loop by calling its main() method. PyApp() gtk.main() It is recommended we add a label “Hello World” in the parent window. label = gtk.Label(“Hello World”) self.add(label) The following is a complete code to display “Hello World”− import gtk class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_default_size(300,200) self.set_title(“Hello World in PyGTK”) label = gtk.Label(“Hello World”) self.add(label) self.show_all() PyApp() gtk.main() The implementation of the above code will yield the following output − Print Page Previous Next Advertisements ”;