Search code examples
python-3.xgtk3pygobject

Change properties through actions


See the example below.

#!/usr/bin/env python3

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gio
import sys

class ApplicationWindow(Gtk.ApplicationWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.set_title("Application")
        self.set_default_size(200, 200)

        grid = Gtk.Grid()
        self.add(grid)

        menubutton = Gtk.MenuButton()
        grid.attach(menubutton, 0, 0, 1, 1)

        label = Gtk.Label.new('AnyLabel')
        grid.attach(label, 0, 1, 1, 1)

        menumodel = Gio.Menu()
        menubutton.set_menu_model(menumodel)
        menumodel.append("New", "app.new")
        menumodel.append("Quit", "app.quit")
        menumodel.append("CLabel", "app.clabel")

class Application(Gtk.Application):

    def do_activate(self):
        window = ApplicationWindow(application=self)
        window.show_all()

    def do_startup(self):
        Gtk.Application.do_startup(self)

        new_action = Gio.SimpleAction.new("new", None)
        new_action.connect("activate", self.new_callback)
        self.add_action(new_action)

        quit_action = Gio.SimpleAction.new("quit", None)
        quit_action.connect("activate", self.quit_callback)
        self.add_action(quit_action)

        clabel_action = Gio.SimpleAction.new("clabel", None)
        clabel_action.connect("activate", self.clabel_callback)
        self.add_action(clabel_action)

    def new_callback(self, action, parameter):
        print("You clicked New")

    def quit_callback(self, action, parameter):
        print("You clicked Quit")
        self.quit()

    def clabel_callback(self, action, parameter):
        """How to change the label here"""


application = Application()
exit_status = application.run(sys.argv)
sys.exit(exit_status)

How to change the label to from the clabel_callback method in Application class?

How clabel_callback method can access label and modify any property?

[off] Notice boring! It don't realize that sometimes code is worth a thousand words


Solution

  • You probably want the action to be a part of your ApplicationWindow then and then you would reference "win.clabel".