Buttons and Stock Images in Python

Thanks to codecademy.com I’ve learnt the basics of Python, and now I’m trying to figure out pygtk. I looked up the tutorial on the pygtk website and even found a package python-gtk2-tutorial on the debian repository. Awesome. In Chapter 6 of the tutorial, there’s an exercise to add an image to a button. Now, the way the author does it is by using a pixmap, but gtk also has a ton of stock images, which you can use.

There is a catch – which is why this blog post’s here! In GTK, it appears that you cannot set a label and an image for a button at the same time, and have them both show by default. If you set the button as a stock.

button = gtk.Button(stock=gtk.STOCK_ADD) – for example, then you’ll see the text "Add".

To allow buttons to have both icons and labels, use the following bit of code before you type window.show()

settings = gtk.settings_get_default()
settings.props.gtk_button_images = True

However, you still can’t use a stock image with a custom label directly. So here’s the workaround:

 button = gtk.Button()
image = gtk.Image()
button.set_label("button 1")
button.connect("clicked", self.callback, "button 1")

(courtesy: https://stackoverflow.com/questions/2188659/stock-icons-not-shown-on-buttons)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s