pygtk and GTK+ tutorial

François Pinard pinard at iro.umontreal.ca
Tue Mar 14 09:43:25 EST 2000


bhoel at server.python.net (Berthold Höllmann) writes:

> I try to learn about GTK+ programming using python.  I read the tutorial
> and port the examples to python.  But I can't get "colorsel.py" working
> properly.  The GtkColorSelectionDialog does not set the drawingarea's
> color.  Any hint, or shall I send my code?

This has been discussed recently on the `pygtk' mailing list: you should
be there.  Here is the way I did it (style may be questionable, I'm still
learning :-).  Note that in `destroy_window', I used `return TRUE' because
the C code did this, but it works more nicely if you write `return FALSE'.

I later found in another experiment that the late allocation of `gc'
in the callback could have been done sooner, but after having called
`window.realize()' within the first few lines of main().  It also seems you
have to call `window.show_now()' instead of `window.show()' if you want
to draw in the window as part of your initialisation.  The documentation
on these things is very terse, so far that I could see :-).



from gtk import *
import GDK

colorseldlg = None
drawingarea = None
gc = None

def color_changed_cb(widget, colorsel):
    window = drawingarea.get_window()
    global gc
    if not gc:
        gc = window.new_gc()
    red, green, blue = colorsel.get_color()
    gc.foreground = window.colormap.alloc(65535*red, 65535*green, 65535*blue)
    # Above could also have been:
    #text = '#%04x%04x%04x' % (65535*red, 65535*green, 65535*blue)
    #gc.foreground = window.colormap.alloc(text)
    draw_rectangle(window, gc, TRUE, 0, 0, window.width, window.height)
    # The above to get around the fact that `window.clear()' is missing.

def area_event(widget, event):
    if event.type == GDK.BUTTON_PRESS and colorseldlg is None:
        global colorseldlg
        colorseldlg = GtkColorSelectionDialog('Select background color')
        colorsel = colorseldlg.colorsel
        colorsel.connect('color_changed', color_changed_cb, colorsel)
        colorseldlg.show()
        return TRUE
    return FALSE

def destroy_window(widget, event):
    mainquit()
    return TRUE

def main():
    window = GtkWindow()
    window.set_title('Color selection test')
    window.set_policy(TRUE, TRUE, TRUE)
    window.connect('delete_event', destroy_window)

    global drawingarea
    drawingarea = GtkDrawingArea()
    drawingarea.size(200, 200)
    drawingarea.set_events(GDK.BUTTON_PRESS_MASK)
    drawingarea.connect('event', area_event)
    window.add(drawingarea)
    drawingarea.show()

    window.show()
    mainloop()

main()

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard






More information about the Python-list mailing list