Search code examples
pythonubuntugtkkeyboard-layoutinput-language

How to change the input language when an entry gets focused in Gtk Python


I want to change the input language when an entry gets focused (or dialog is shown) in Gtk Python. In my program, a dialog appears many times and the user must enter some texts. In systems which allow different keyboard layout for each window, the user must change the input language each time the dialog is appearing. I am programming on ubuntu ...


Solution

  • My first approach was be to look at Gtk+ input methods.

    The Gtk.Entry has the property im_module, which can be used to set the Gtk.IMContext. There also two blogpost (1, 2) and an extensive Stackoverflow Answer about Gtk+ input methods that may help you.

    My second approach was to use xkb.

    You could try something like

    subprocess.run('sudo setxkbmap -layout ' + entry_lang_str)

    And then I remembered that you could also use gsettings.

    gsettings set /org/gnome/desktop/input-sources/ sources [('xkb', entr_lang_str)] (also via subprocess.run())

    Using gsettings seems to be the easiest way for me.