Gurjot Singh Mahi
Gurjot Singh Mahi

Reputation: 101

Text Widget does not display Unicode Characters

I am working on a regional language text editor, which takes the regional Unicode characters (script that I am using is Gurmukhi and Unicode compatible font is Raavi) from text widget and prints it on the terminal screen.

Now problem arises when I copy and paste some characters strings into the text widget, it get convert into the boxes as shown in the image, but it prints perfect string on terminal window.

Although I have tried encoding and decoding functionality from codecs, but, that too gets in vain.

I cannot find any answer related to Unicode entry mechanism for Text widget in Tkinter.

How we can show perfect unicode string ਸਤਵਿੰਦਰ in text widget?

Here is my code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tkinter.font as tkFont
from tkinter import *

def retrieve_input(self):
    inputValue = content_text.get("1.0", "end-1c")
    print(inputValue)

root = Tk()
root.call('encoding', 'system', 'utf-8')
customFont = tkFont.Font(family='Raavi', size=17)
root.title("Unicode Handling")
root.geometry('400x200+150+200')
content_text = Text(root, wrap='word', font=customFont)
content_text.configure(font=customFont)
content_text.focus_set()
content_text.pack(expand='yes', fill='both')
scroll_bar = Scrollbar(content_text)
content_text.configure(yscrollcommand=scroll_bar.set)
scroll_bar.config(command=content_text.yview)
scroll_bar.pack(side='right', fill='y')
root.bind("<space>", retrieve_input)
root.mainloop()

Here is input and output:

Input and Output

Upvotes: 2

Views: 4900

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385950

How we can show perfect unicode string ਸਤਵਿੰਦਰ in text widget?

Your code should work, assuming you have the correct font installed. I've reduced your code to a more minimal example:

import tkinter.font as tkFont
from tkinter import *

root = Tk()
customFont = tkFont.Font(family='Raavi', size=17)
content_text = Text(root, font=customFont, width=20, height=4)
content_text.pack(expand='yes', fill='both')
content_text.insert("end", 'ਸਤਵਿੰਦਰ')

root.mainloop()

On my system this results in the following:

screenshot of tkinter window

When I print the results of customFont.actual() I get the following (I don't have the "Ravii" font installed so tkinter will substitute a fallback font, which may be different on your system):

{
    'slant': 'roman', 
    'underline': 0, 
    'size': 17, 
    'family': 'DejaVu Sans', 
    'overstrike': 0, 
    'weight': 'normal'
}

To see a list of all of the font families that your installation of tkinter will recognize, run this code:

from tkinter import font, Tk

root = Tk()
print(font.families())

Upvotes: 3

Related Questions