A FontChooserWidget with a callback function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
from gi.repository import Gtk import sys class MyWindow(Gtk.ApplicationWindow): def __init__(self, app): Gtk.Window.__init__(self, title="FontChooserWidget", application=app) # a font chooser self.font_chooser = Gtk.FontChooserWidget() # a default font self.font_chooser.set_font("Sans") # a text to preview the font self.font_chooser.set_preview_text( "This is an example of preview text!") # connect signal from the font chooser to the callback function self.font_chooser.connect("notify::font", self.font_cb) # add the font chooser to the window self.add(self.font_chooser) # callback function: def font_cb(self, event, user_data): # print in the terminal print("You chose the font " + self.font_chooser.get_font()) class MyApplication(Gtk.Application): def __init__(self): Gtk.Application.__init__(self) def do_activate(self): win = MyWindow(self) win.show_all() def do_startup(self): Gtk.Application.do_startup(self) app = MyApplication() exit_status = app.run(sys.argv) sys.exit(exit_status)
In line 16 the "notify::font" signal from the widget is connected to the callback function font_cb() using widget.connect(signal, callback function). See Signals and callbacks for a more detailed explanation.
To set the font which is initially selected, use set_font(font) (where font is the font name) or set_font_desc(font) (where font is the PangoFontDescription).
To get the selected font use get_font() or get_font_desc().
To change the text which is shown in the preview area, use set_preview_text().
In this sample we used the following:
Got a comment? Spotted an error? Found the instructions unclear? Send feedback about this page.