Skip to content

Instantly share code, notes, and snippets.

@nzjrs
Created February 24, 2013 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nzjrs/5023610 to your computer and use it in GitHub Desktop.
Save nzjrs/5023610 to your computer and use it in GitHub Desktop.
A PyGObject / GTK implementation of a solid color GtkButton
import numpy
import cairo
from math import pi
from gi.repository import Gtk,Gdk
def draw_rounded(cr, area, radius):
a,b,c,d=area
cr.arc(a + radius, c + radius, radius, 2*(pi/2), 3*(pi/2))
cr.arc(b - radius, c + radius, radius, 3*(pi/2), 4*(pi/2))
cr.arc(b - radius, d - radius, radius, 0*(pi/2), 1*(pi/2)) # ;o)
cr.arc(a + radius, d - radius, radius, 1*(pi/2), 2*(pi/2))
cr.close_path()
def remove_button_padding(button):
data = """.button {
-GtkWidget-focus-line-width : 0px;
-GtkWidget-focus-padding : 0px;
padding: 0px;
}"""
provider = Gtk.CssProvider()
provider.load_from_data(data)
# 600 = GTK_STYLE_PROVIDER_PRIORITY_APPLICATION
button.get_style_context().add_provider(provider, 600)
class ColorGtkButton(Gtk.Button):
def __init__(self, rgb, *args, **kwargs):
Gtk.Button.__init__(self, *args, **kwargs)
self.add(ColorGtkImage(rgb, Gtk.IconSize.BUTTON, None))
remove_button_padding(self)
class ColorGtkImage(Gtk.Image):
def __init__(self, rgb, size, radius, *args, **kwargs):
Gtk.Image.__init__(self, *args, **kwargs)
if type(size) is Gtk.IconSize:
_,w,h = Gtk.icon_size_lookup(size)
else:
w,h = size
r,g,b = map(float,rgb)
lw = 1
radius = min(w/7.0,10) if radius is None else radius
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w,h)
cr = cairo.Context(surface)
cr.set_line_width(lw)
cr.set_source_rgb(r,g,b)
area = (lw, w-lw, lw, h-lw) #top,btm,left,right
draw_rounded(cr,area,radius)
cr.fill()
pb = Gdk.pixbuf_get_from_surface(surface,0,0,w,h)
self.set_from_pixbuf(pb)
if __name__ == "__main__":
box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
box.add(
ColorGtkButton((1,0,0))
)
box.add(
ColorGtkButton((0,1,0))
)
w = Gtk.Window()
w.connect("delete-event", Gtk.main_quit)
w.add(box)
w.show_all()
Gtk.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment