Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use arabic text with tkinter

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

like image 485
Mohab Mostafa Avatar asked Dec 12 '25 03:12

Mohab Mostafa


1 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
from awesometkinter.bidirender import add_bidi_support
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
add_bidi_support(lbl)
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 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

like image 171
Mahmoud Elshahat Avatar answered Dec 14 '25 17:12

Mahmoud Elshahat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!