Use arabic text with tkinter

Viewed 467

I want to use Arabic language in my python app but it doesn't work. I tried the following:

   #!/usr/bin/env python3
   # -*- coding: UTF-8 -*-
   .
   .
   .
   welcMsg = 'مرحبا'
   welcome_label = ttk.Label(header, text=welcMsg, font=(
   "KacstBook", 24)).grid(row=0, column=0, pady=20)

I also tried to add

   welcMsg = welcMsg.encode("windows-1256", "ignore")

but the result is always like this

enter image description here

and it also happens with tkinter Entry and Text

   searchField = ttk.Entry(tab3, width=50)
   textBox = Text(tab4, width=45, height=15, font=("KacstOffice", 16), selectbackground="yellow",
           selectforeground="black", undo=True, yscrollcommand=text_scroll.set, wrap=WORD)

so is there anything else I can try to work with Label, Entry and Text?

NOTE: I am using Ubuntu 18.04 bionic

2 Answers

Tkinter doesn't have a bidi support (According to tk's source code), which means RTL(Right-To-Left) languages like Arabic will be displayed incorrectly with 2 problems:

1- letters will be displayed in reverse order.

2- letters are not joined correctly.

the reason Arabic is being displayed correctly on windows is because bidi support is handled by operating system, and this is not the case in Linux

to fix this problem on linux you can use AwesomeTkinter package, it can add bidi support to labels and entry (also while editing)

import tkinter as tk
import awesometkinter as atk
root = tk.Tk()

welcMsg = 'مرحبا'

# text display incorrectly on linux without bidi support
tk.Label(root, text=welcMsg).pack()

entry = tk.Entry(root, justify='right')
entry.pack()

lbl = tk.Label(root)
lbl.pack()

# adding bidi support for widgets
atk.add_bidi_support(lbl)
atk.add_bidi_support(entry)

# Now we have a new set() and get() methods to set and get text on a widget
# these methods added by atk.add_bidi_support() and doesn't exist in standard widgets.
entry.set(welcMsg)
lbl.set(welcMsg)

root.mainloop()

output:

enter image description here

note: you can install awesometkinter by pip install awesometkinter

You simply need to set your encoding to UTF-8 by making this line the first one (before your code) in your Python file: # -- coding: UTF-8 --

This is a code sample:

# -*- coding: UTF-8 -*-
from Tkinter import *
root = Tk()
root.title('Alram')
root.geometry("1500x600")
mytext= 'ذكرت تقارير' #Arabic text
msg = Message(root, bg="red", text= mytext, justify='right')
msg.config(font=('times', 72, 'bold'))
exit_button = Button(root, width=10, text='Exit', command=root.destroy)
exit_button.pack()
msg.pack(fill=X)
root.mainloop()

here is the original answer: Arabic text in TKinter

Related