Inspirated

 
 

August 30, 2009

HOWTO: Add grid lines to a GtkDrawingArea in PyGTK

Filed under: Blog — krkhan @ 6:29 pm

Recently, I needed to create some visualizations in a drawing area for one of my PyGTK apps. The PyGTK tutorial had an excellent writeup complete with a working example for immediate help. Unfortunately, my requirements were of a “grid” view on which other objects would be drawn. Naturally, I hoped for some variable on the GtkDrawingArea which I would set to true and have the grid lines drawn automatically. But since I couldn’t find any such magic setting in the API, I had to draw the lines manually.

Consequently, I could use either of the following approaches:

  • Loop horizontally and vertically while draw_line()ing.
  • Draw a 10×10 box as a tile and repeat it over the background.

The first approach would’ve worked faster but involved writing more code. The second was uglier — especially for larger images — but resulted in me having to add only a few lines to the example:

72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        xpm_data = ["10 10 2 1",
            " 	c #EEEEEE",
            ".	c #FFFFFF",
            "          ",
            " ........ ",
            " ........ ",
            " ........ ",
            " ........ ",
            " ........ ",
            " ........ ",
            " ........ ",
            " ........ ",
            "          "]
        tile_pixmap, tile_mask = gtk.gdk.pixmap_create_from_xpm_d(
            area.window, None, xpm_data)
        tile_gc = area.window.new_gc(fill = gtk.gdk.TILED,
            tile = tile_pixmap)
        width = int(self.hruler.get_range()[3])
        height = int(self.vruler.get_range()[3])
        area.window.draw_rectangle(tile_gc, True, 0, 0, width, height)

Turning this:

GtkDrawingArea Example

Into this:

GtkDrawingArea Grid Example

Note that the 10×10 tiles’ borders match prettily with the markers on top and left rulers. There will definitely be some more efficient method for achieving this but for the time being tiling serves my needs perfectly.

Tags: , , , , , , ,

1 Comment

  1. […] hacerlo me base en un ejemplo hecho en phyton y este fue el […]

    Pingback by Simple Diagram Editor in Ruby + Gtk2 | tripabyte — July 17, 2011 @ 10:08 pm

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.