I'm assembling a GUI using PyGObject. This Python code works in context. I get a toolbar button with the stock "Open" icon.
from gi.repository import Gtk
# ...
toolbar = Gtk.Toolbar()
toolbar.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR)
# ...
self.fileOpen = Gtk.ToolButton.new_from_stock(Gtk.STOCK_OPEN)
self.fileOpen.connect("clicked", self.on_FileOpenStandard_activate)
toolbar.insert(self.fileOpen, -1)
But according to this resource, new_from_stock()
is deprecated:
Deprecated since version 3.10: Use
Gtk.ToolButton.new ()
together withGtk.Image.new_from_icon_name ()
instead.
Okay then. So after digging further, this is what I came up with for a replacement:
self.fileOpen = Gtk.ToolButton(
Gtk.Image.new_from_icon_name("document-open",
Gtk.IconSize.LARGE_TOOLBAR),
"Open")
self.fileOpen.connect("clicked", self.on_FileOpenStandard_activate)
toolbar.insert(self.fileOpen, -1)
But this is the result:
What is the correct way to do this that is still supported by the current GTK library?
Looking at this C++ GitHub example, I'm surprised to discover a direct call to the static new()
function rather than the constructor.
So I decided to try it. Look carefully at the difference. It's subtle.
#vvv
self.fileOpen = Gtk.ToolButton.new(
Gtk.Image.new_from_icon_name("document-open",
Gtk.IconSize.LARGE_TOOLBAR),
"Open")
self.fileOpen.connect("clicked", self.on_FileOpenStandard_activate)
toolbar.insert(self.fileOpen, -1)
To my surprise, this displays the icon where the other approach does not.
Bonus: Cleaner version of the above:
# iconSize to be reused
iconSize = Gtk.IconSize.LARGE_TOOLBAR
# ...
openIcon = Gtk.Image.new_from_icon_name("document-open", iconSize)
self.fileOpen = Gtk.ToolButton.new(openIcon, "Open")
self.fileOpen.connect("clicked", self.on_FileOpenStandard_activate)
toolbar.insert(self.fileOpen, -1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With