Introduction

WxPython and Cairo can work well together, but it can be slightly daunting to figure out exactly how to get a basic working piece of code to build off of, especially if your experience with WxWidgets is limited. This page should help get you started.

It should be noted that wx.lib.wxcairo still requires Cairo and PyCairo to be installed. This can be an ordeal on Windows. Refer to this page for help.

What Objects are Involved

Process Overview

Special Concerns

Code Sample

   1 import wx
   2 try:
   3         import wx.lib.wxcairo
   4         import cairo
   5         haveCairo = True
   6 except ImportError:
   7         haveCairo = False
   8 
   9 class MyFrame(wx.Frame):
  10         def __init__(self, parent, title):
  11                 wx.Frame.__init__(self, parent, title=title, size=(640,480))
  12                 self.canvas = CairoPanel(self)
  13                 self.Show()
  14 
  15 class CairoPanel(wx.Panel):
  16         def __init__(self, parent):
  17                 wx.Panel.__init__(self, parent, style=wx.BORDER_SIMPLE)
  18                 self.Bind(wx.EVT_PAINT, self.OnPaint)
  19                 self.text = 'Hello World!'
  20 
  21         def OnPaint(self, evt):
  22                 #Here we do some magic WX stuff.
  23                 dc = wx.PaintDC(self)
  24                 width, height = self.GetClientSize()
  25                 cr = wx.lib.wxcairo.ContextFromDC(dc)
  26 
  27                 #Here's actual Cairo drawing
  28                 size = min(width, height)
  29                 cr.scale(size, size)
  30                 cr.set_source_rgb(0, 0, 0) #black
  31                 cr.rectangle(0, 0, width, height)
  32                 cr.fill()
  33 
  34                 cr.set_source_rgb(1, 1, 1) #white               
  35                 cr.set_line_width (0.04)
  36                 cr.select_font_face ("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
  37                 cr.set_font_size (0.07)
  38                 cr.move_to (0.5, 0.5)
  39                 cr.show_text (self.text)
  40                 cr.stroke ()
  41 
  42         #Change what text is shown
  43         def SetText(self, text):
  44                 self.text = text
  45                 self.Refresh()
  46 
  47 if haveCairo:
  48         app = wx.App(False)
  49         theFrame = MyFrame(None, 'Barebones Cairo Example')
  50         app.MainLoop()
  51 else:
  52         print "Error! PyCairo or a related dependency was not found"

Comments

UsingCairoTheEasyWay (last edited 2010-06-16 09:41:15 by JamesGecko)