Changing the default input language in tkinter text widget

873 views Asked by At

Is there any way to change the default input language in tkinter?

Here's the code:

from tkinter import *

root = Tk()

text = Text(root , width = 65 , height = 20 , font = "consolas 14")
text.pack()

mainloop()

Here, when I type some text into the text widget, it is being typed in english.

What I want is to type the text in some other language.

Is there any way to achieve this in tkinter?

It would be great if anyone could help me out.

1

There are 1 answers

2
Tls Chris On

On my MacOS PC, UK Keyboard, I can use various key combinations to get German and French characters. Alt-a: å
Alt e followed by e: é
Alt u followed by o: ö or by u: ü by a: ä by A: Ä
Alt i followed by a: â
Step 1 would be to experiment with that.

2nd Option If only a few characters are required map them to e.g. the F Keys

import tkinter as tk

root = tk.Tk()

text = tk.Text( root, width = 50, height = 20, font = ( 'Arial', 20 ) )
text.grid()

key_map =  { 'F5': 'ü', 'F6': 'ö', 'F13': 'ß', 'F14': 'á', 'F15': 'é' }
# Map the function keys to the characters required.
# f5, f6, f13, etc return the mapped characters.
# The other F keys are used for system activities from my keyboard.

def do_key( event ):
    char = key_map.get( event.keysym )
    if char:
        text.insert( tk.INSERT, char )
        return 'break'  # Stops the event being passed to the text box.

text.bind( '<KeyPress>', do_key )

root.mainloop()

3rd Option A more thorough approach may be to open a second 'keyboard' window that can send characters to the text box.

import tkinter as tk

root = tk.Tk()

text = tk.Text( root, width = 50, height = 20, font = ( 'Arial', 20 ) )
text.grid()

key_map =  { 'F5': 'ü', 'F6': 'ö', 'F13': 'ß', 'F14': 'á', 'F15': 'é' }

def make_keys( char ):
    def do_key():
        text.insert( tk.INSERT, char )
        return 'break'
    return do_key

def get_key( event ):
    master = tk.Toplevel( root )
    for col, v in enumerate( key_map.values()):
        tk.Button( master, text = v, command = make_keys( v )).grid( row = 0, column = col )
    return 'break'

text.bind( '<KeyPress-F5>', get_key )
# Press F5 in the text box to open the keyboard.

root.mainloop()

With this option the extra window could be permanently open or a further frame in the GUI instead of a separate window.

There may be OS specific ways of doing this more neatly or options in tkinter that I don't know about but this should give some ideas to explore.