[pygtk] Drawing on custom widgets with colour

Tuomas Launiainen tuomas.launiainen at iki.fi
Thu Jul 26 22:26:26 WST 2007


Hello

I'm experimenting with custom widgets in pygtk, and I can't get drawing
to work with colours. I'm using the following method to do the actual
drawing:

  def do_expose_event(self, event):
    self.gc.set_foreground(gtk.gdk.color_parse("red"))
    self.gc.set_background(gtk.gdk.color_parse("red"))
    self.window.draw_rectangle(self.gc,True,0,0,self.allocation.width,self.allocation.height)

The result is a black rectangle, but I expected a red one.

gtk.gtk_version is (2, 8, 20), and gtk.pygtk_version is (2, 8, 6). The
full code is:

#!/usr/bin/env python
import gtk
import gobject
from signal import *

class MyWidget(gtk.Widget):
  def __init__(self):
    gtk.Widget.__init__(self)
  def do_realize(self):
    self.set_flags(self.flags() | gtk.REALIZED)
    self.window = gtk.gdk.Window(
      self.get_parent_window(),
      width=self.allocation.width,
      height=self.allocation.height,
      window_type=gtk.gdk.WINDOW_CHILD,
      wclass=gtk.gdk.INPUT_OUTPUT,
      event_mask=self.get_events() | gtk.gdk.EXPOSURE_MASK)
    self.window.set_user_data(self)
    self.style.attach(self.window)
    self.style.set_background(self.window, gtk.STATE_NORMAL)
    self.window.move_resize(*self.allocation)
    self.gc=self.window.new_gc()
  def do_unrealize(self):
    self.window.set_user_data(None)
  def do_size_request(self, requisition):
    requisition.width=50
    requisition.height=60
  def do_size_allocate(self, allocation):
    self.allocation = allocation
    if self.flags() & gtk.REALIZED:
      self.window.move_resize(*allocation)
  def do_expose_event(self, event):
    self.gc.set_foreground(gtk.gdk.color_parse("red"))
    self.gc.set_background(gtk.gdk.color_parse("red"))
    self.window.draw_rectangle(self.gc,True,0,0,self.allocation.width,self.allocation.height)

gobject.type_register(MyWidget)

def quit(*a):
  gtk.main_quit()
  return False

if __name__=="__main__":
  for s in (SIGHUP,SIGINT,SIGQUIT,SIGTERM):
    signal(s,quit)
  win=gtk.Window(gtk.WINDOW_TOPLEVEL)
  win.connect("destroy",quit)

  win.add(MyWidget())

  win.show_all()
  gtk.main()


More information about the pygtk mailing list