Gtk.Application
Gtk.Application — Application class
Object Hierarchy:
GObject
╰── GApplication
╰── Gtk.Application
Functions:
- new
(application_id:str=None, flags:Gio.ApplicationFlags) -> Gtk.Application
- add_window
(self, window:Gtk.Window)
- remove_window
(self, window:Gtk.Window)
- get_windows
(self) -> list
- get_window_by_id
(self, id:int) -> Gtk.Window
- get_active_window
(self) -> Gtk.Window
- inhibit
(self, window:Gtk.Window=None, flags:Gtk.ApplicationInhibitFlags, reason:str=None) -> int
- uninhibit
(self, cookie:int)
- is_inhibited
(self, flags:Gtk.ApplicationInhibitFlags) -> bool
- prefers_app_menu
(self) -> bool
- get_app_menu
(self) -> Gio.MenuModel
- set_app_menu
(self, app_menu:Gio.MenuModel=None)
- get_menubar
(self) -> Gio.MenuModel
- set_menubar
(self, menubar:Gio.MenuModel=None)
- get_menu_by_id
(self, id:str) -> Gio.Menu
- add_accelerator
(self, accelerator:str, action_name:str, parameter:GLib.Variant=None)
- remove_accelerator
(self, action_name:str, parameter:GLib.Variant=None)
- list_action_descriptions
(self) -> list
- get_accels_for_action
(self, detailed_action_name:str) -> list
- set_accels_for_action
(self, detailed_action_name:str, accels:list)
- get_actions_for_accel
(self, accel:str) -> list
Signals:
- “window-added”
(application, window, user_data)
- “window-removed”
(application, window, user_data)
Description:
Gtk.Application
is a class that handles many important aspects of a GTK+ application in a convenient fashion, without enforcing a one-size-fits-all application model.
Currently, Gtk.Application
handles GTK+ initialization, application uniqueness, session management, provides some basic scriptability and desktop shell integration by exporting actions and menus and manages a list of toplevel windows whose life-cycle is automatically tied to the life-cycle of your application.
While Gtk.Application
works fine with plain GtkWindows, it is recommended to use it together with Gtk.ApplicationWindow.
When GDK threads are enabled, Gtk.Application
will acquire the GDK lock when invoking actions that arrive from other processes. The GDK lock is not touched for local action invocations. In order to have actions invoked in a predictable context it is therefore recommended that the GDK lock be held while invoking actions locally with Gio.ActionGroup::activate_action()
. The same applies to actions associated with Gtk.ApplicationWindow and to the activate
and open Gio.Application
methods.
Automatic resources
Gtk.Application
will automatically load menus from the GtkBuilder file located at "gtk/menus.ui", relative to the application's resource base path (see Gio.Application::set_resource_base_path()
). The menu with the ID "app-menu" is taken as the application's app menu and the menu with the ID "menubar" is taken as the application's menubar. Additional menus (most interesting submenus) can be named and accessed via Gtk.Application::get_menu_by_id()
which allows for dynamic population of a part of the menu structure.
If the files "gtk/menus-appmenu.ui" or "gtk/menus-traditional.ui" are present then these files will be used in preference, depending on the value of Gtk.Application::prefers_app_menu()
.
It is also possible to provide the menus manually usingGtk.Application::set_app_menu()
and Gtk.Application::set_menubar()
.
Gtk.Application
will also automatically setup an icon search path for the default icon theme by appending "icons" to the resource base path. This allows your application to easily store its icons as resources. See Gtk.IconTheme::add_resource_path()
for more information.
A simple application
A simple example at the bottom.
Gtk.Application
optionally registers with a session manager of the users session (if you set the Gtk.Application::register-session property
) and offers various functionality related to the session life-cycle.
An application can block various ways to end the session with the Gtk.Application::inhibit()
function. Typical use cases for this kind of inhibiting are long-running, uninterruptible operations, such as burning a CD or performing a disk backup. The session manager may not honor the inhibitor, but it can be expected to inform the user about the negative consequences of ending the session while inhibitors are present.
See Also
[Getting Started with Python GTK+: Basics]
Function Details:
new()
new (application_id:str=None, flags:Gio.ApplicationFlags) -> Gtk.Application
Creates a new Gtk.Application
instance.
When using Gtk.Application
, it is not necessary to call Gtk.init`()`manually. It is called as soon as the application gets registered asthe primary instance.
Concretely,
Gtk.init()
is called in the default handler for the“startup” signal. Therefore, Gtk.Application
subclasses shouldchain up in their “startup” handler before using any GTK+ API.
Note that commandline arguments are not passed to Gtk.init`()`.All GTK+ functionality that is available via commandline argumentscan also be achieved by setting suitable environment variablessuch as `G_DEBUG`, so this should not be a bigproblem. If you absolutely must support GTK+ commandline arguments,you can explicitly call
Gtk.init()
before creating the applicationinstance.
If non-None
, the application ID must be valid. Seeg_application_id_is_valid()
.
If no application ID is given then some features (most notably application uniqueness) will be disabled. A null application ID is only allowed with GTK+ 3.6 or later.
Returns: a new
Gtk.Application
instanceSince: 3.0
add_window()
add_window (self, window:Gtk.Window)
Adds a window to application
.
This call can only happen after the application
has started;typically, you should add new application windows in responseto the emission of the “activate” signal.
This call is equivalent to setting the “application”property of window
to application
.
Normally, the connection between the application and the windowwill remain until the window is destroyed, but you can explicitlyremove it with Gtk.Application:remove_window()
.
GTK+ will keep the application
running as long as it hasany windows.
- Since: 3.0
remove_window()
remove_window (self, window:Gtk.Window)
Remove a window from application
.
If window
belongs to application
then this call is equivalent tosetting the “application” property of window
toNone
.
The application may stop running as a result of a call to thisfunction.
- Since: 3.0
get_windows()
get_windows (self) -> list
Gets a list of the Gtk.Windows
associated with application
.
The list is sorted by most recently focused window, such that the firstelement is the currently focused window. (Useful for choosing a parentfor a transient window.)
The list that is returned should not be modified in any way. It willonly remain valid until the next focus change or window creation ordeletion.
Returns: a GList of
Gtk.Window
.Since: 3.0
get_window_by_id()
get_window_by_id (self, id:int) -> Gtk.Window
Returns the Gtk.ApplicationWindow
with the given ID.
Returns: the window with ID
id
, orNone
if there is no window with this ID.Since: 3.6
get_active_window()
get_active_window (self) -> Gtk.Window
Gets the “active” window for the application. The active window is the one that was most recently focused (withinthe application). This window may not have the focus at the momentif another application has it — this is just the mostrecently-focused window within this application.
Returns: the active window.
Since: 3.6
inhibit()
inhibit (self, window:Gtk.Window=None, flags:Gtk.ApplicationInhibitFlags, reason:str=None) -> int
Inform the session manager that certain types of actions should beinhibited. This is not guaranteed to work on all platforms and forall types of actions.
Applications should invoke this method when they begin an operationthat should not be interrupted, such as creating a CD or DVD. Thetypes of actions that may be blocked are specified by the flags
parameter. When the application completes the operation it shouldcall Gtk.Application:uninhibit()
to remove the inhibitor. Note thatan application can have multiple inhibitors, and all of the mustbe individually removed. Inhibitors are also cleared when theapplication exits.
Applications should not expect that they will always be able to blockthe action. In most cases, users will be given the option to forcethe action to take place.
Reasons should be short and to the point.
If window
is given, the session manager may point the user tothis window to find out more about why the action is inhibited.
Returns: A non-zero cookie that is used to uniquely identify thisrequest. It should be used as an argument to
Gtk.Application:uninhibit()
in order to remove the request. If the platform does not supportinhibiting or the request failed for some reason, 0 is returned.Since: 3.4
uninhibit()
uninhibit (self, cookie:int)
Removes an inhibitor that has been established with Gtk.Application:inhibit()
.Inhibitors are also cleared when the application exits.
- Since: 3.4
is_inhibited()
is_inhibited (self, flags:Gtk.ApplicationInhibitFlags) -> bool
Determines if any of the actions specified in flags
arecurrently inhibited (possibly by another application).
Returns:
True
if any of the actions specified inflags
are inhibitedSince: 3.4
prefers_app_menu()
prefers_app_menu (self) -> bool
Determines if the desktop environment in which the application isrunning would prefer an application menu be shown.
If this function returns True
then the application should callGtk.Application:set_app_menu()
with the contents of an applicationmenu, which will be shown by the desktop environment. If it returnsFALSE
then you should consider using an alternate approach, such asa menubar.
The value returned by this function is purely advisory and you arefree to ignore it. If you call Gtk.Application:set_app_menu()
evenif the desktop environment doesn't support app menus, then a fallbackwill be provided.
Applications are similarly free not to set an app menu even if thedesktop environment wants to show one. In that case, a fallback willalso be created by the desktop environment (GNOME, for example, usesa menu with only a "Quit" item in it).
The value returned by this function never changes. Once it returns aparticular value, it is guaranteed to always return the same value.
You may only call this function after the application has beenregistered and after the base startup handler has run. You're mostlikely to want to use this from your own startup handler. It mayalso make sense to consult this function while constructing UI (inactivate, open or an action activation handler) in order to determineif you should show a gear menu or not.
This function will return FALSE
on Mac OS and a default app menuwill be created automatically with the "usual" contents of that menutypical to most Mac OS applications. If you callGtk.Application:set_app_menu()
anyway, then this menu will bereplaced with your own.
Returns:
True
if you should set an app menuSince: 3.14
get_app_menu()
get_app_menu (self) -> Gio.MenuModel
Returns the menu model that has been set withGtk.Application:set_app_menu()
.
Returns: the application menu of
application
.Since: 3.4
set_app_menu()
set_app_menu (self, app_menu:Gio.MenuModel=None)
Sets or unsets the application menu for application
.
This can only be done in the primary instance of the application,after it has been registered. “startup” is a good placeto call this.
The application menu is a single menu containing items that typicallyimpact the application as a whole, rather than acting on a specificwindow or document. For example, you would expect to see“Preferences” or “Quit” in an application menu, but not “Save” or“Print”.
If supported, the application menu will be rendered by the desktopenvironment.
Use the base GActionMap interface to add actions, to respond to the userselecting these menu items.
- Since: 3.4
get_menubar()
get_menubar (self) -> Gio.MenuModel
Returns the menu model that has been set withGtk.Application:set_menubar()
.
Returns: the menubar for windows of
application
.Since: 3.4
set_menubar()
set_menubar (self, menubar:Gio.MenuModel=None)
Sets or unsets the menubar for windows of application
.
This is a menubar in the traditional sense.
This can only be done in the primary instance of the application,after it has been registered. “startup” is a good placeto call this.
Depending on the desktop environment, this may appear at the top ofeach window, or at the top of the screen. In some environments, ifboth the application menu and the menubar are set, the applicationmenu will be presented as if it were the first item of the menubar.Other environments treat the two as completely separate — for example,the application menu may be rendered by the desktop shell while themenubar (if set) remains in each individual window.
Use the base GActionMap interface to add actions, to respond to theuser selecting these menu items.
- Since: 3.4
get_menu_by_id()
get_menu_by_id (self, id:str) -> Gio.Menu
Gets a menu from automatically loaded resources.See Automatic resourcesfor more information.
Returns: Gets the menu with thegiven id from the automatically loaded resources.
Since: 3.14
add_accelerator()
add_accelerator (self, accelerator:str, action_name:str, parameter:GLib.Variant=None)
Gtk.Application:add_accelerator
has been deprecated since version 3.14 and should not be used in newly-written code.
Use Gtk.Application:set_accels_for_action()
instead
Installs an accelerator that will cause the named actionto be activated when the key combination specificed by accelerator
is pressed.
accelerator
must be a string that can be parsed by `Gtk.Accelerator:parse
(),e.g. "<Primary>q" or “<Control><Alt>p”.
action_namemust be the name of an action as it would be usedin the app menu, i.e. actions that have been added to the applicationare referred to with an “app.” prefix, and window-specific actionswith a “win.” prefix.
Gtk.Applicationalso extracts accelerators out of “accel” attributesin the GMenuModels passed to
Gtk.Application:set_app_menu()and
Gtk.Application:set_menubar()`, which is usually more convenientthan calling this function for each accelerator.
- Since: 3.4
remove_accelerator()
remove_accelerator (self, action_name:str, parameter:GLib.Variant=None)
Gtk.Application:remove_accelerator
has been deprecated since version 3.14 and should not be used in newly-written code.
Use Gtk.Application:set_accels_for_action()
instead
Removes an accelerator that has been previously addedwith Gtk.Application:add_accelerator()
.
- Since: 3.4
list_action_descriptions()
list_action_descriptions (self) -> list
Lists the detailed action names which have associated accelerators.See Gtk.Application:set_accels_for_action()
.
Returns: a
None
-terminated array of strings,free withg_strfreev()
when done.Since: 3.12
get_accels_for_action()
get_accels_for_action (self, detailed_action_name:str) -> list
Gets the accelerators that are currently associated withthe given action.
Returns: accelerators for
detailed_action_name
, asaNone
-terminated array. Free withg_strfreev()
when no longer needed.Since: 3.12
set_accels_for_action()
set_accels_for_action (self, detailed_action_name:str, accels:list)
Sets zero or more keyboard accelerators that will trigger thegiven action. The first item in accels
will be the primaryaccelerator, which may be displayed in the UI.
To remove all accelerators for an action, use an empty, zero-terminatedarray for accels
.
- Since: 3.12
get_actions_for_accel()
get_actions_for_accel (self, accel:str) -> list
Returns the list of actions (possibly empty) that accel
maps to.Each item in the list is a detailed action name in the usual form.
This might be useful to discover if an accel already exists inorder to prevent installation of a conflicting accelerator (froman accelerator editor or a plugin system, for example). Note thathaving more than one action per accelerator may not be a bad thingand might make sense in cases where the actions never appear in thesame context.
In case there are no actions for a given accelerator, an empty arrayis returned. None
is never returned.
It is a programmer error to pass an invalid accelerator string.If you are unsure, check it with `Gtk.Accelerator:parse
()` first.
Returns: a
None
-terminated array of actions foraccel
.Since: 3.14
Example:
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, application):
Gtk.Window.__init__(self, application=application)
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)
menumodel = Gio.Menu()
menubutton.set_menu_model(menumodel)
menumodel.append("New", "app.new")
menumodel.append("Quit", "app.quit")
class Application(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self)
def do_activate(self):
window = ApplicationWindow(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)
def new_callback(self, action, parameter):
print("You clicked New")
def quit_callback(self, action, parameter):
print("You clicked Quit")
self.quit()
application = Application()
exit_status = application.run(sys.argv)
sys.exit(exit_status)