[Builder] Challenges Binding Buttons to Python Code



Hi Builders,

As good opportunities arise, I'd like to share my challenges as a developer new to using Builder for a Python + GTK GUI + Flatpak app. In this case, I think I'm past the problem, but I suspect others might benefit from me sharing how I got past it. I'm also not sure my solution is the best practice, so maybe I still need guidance, too.

I've started all of my work using the Builder Python GTK project template. I use Fedora 30 Silverblue and the latest Builder package from Flathub.

My first challenge was binding the click event of a button (created in window.ui) so that it runs code in Python. After reading some Python GTK documentation, I quickly found that GTK uses signals for handling such events. However, this wasn't obvious from the UI builder offering "Action Name" as the main binding for the button.

The bigger challenge was how I'd link that action/signal to Python code. Most documentation for Python/Glade-style work assumes either:
  • Controls get instantiated in code, allowing binding at control instantiation [1]
  • Code instantiates the controls via a "builder" object [2]
Starting from the Builder Python GTK project template, neither seemed to apply. So, the best I've come up with to bind buttons in the UI to signals is the following.

For the application-level action case, on the button in the UI designer, I set "Action Name" to be "app.foo". Then, in main.py, I altered the Application class to add the following:

class Application(Gtk.Application):
    def __init__(self):
        # Superclass init call truncated
        foo_action = Gio.SimpleAction.new("foo", None)
        foo_action.connect("activate", self.foo_callback)
        self.add_action(foo_action)

    def foo_callback(self, action, parameter):
        print("foo_callback")

For the window-level action case, I set "Action Name" to "win.foo". Then, in window.py, I altered the subclass of Gtk.ApplicationWindow the same way as the Application class above. I also added "Gio" to the imports alongside "Gtk".

Am I on the right track? One of the things I really liked from my (long ago) Microsoft Access/Visual Basic years was being able to right-click on a button, select something like "Go to code..." on the context menu, and land in the right method. If the method didn't already exist, it got created.

[1] https://python-gtk-3-tutorial.readthedocs.io/en/latest/introduction.html#extended-example
[2] https://python-gtk-3-tutorial.readthedocs.io/en/latest/builder.html


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]