在 tkinter 中使用阿拉伯语文本

问题描述

我想在我的 python 应用程序中使用阿拉伯语,但它不起作用。我尝试了以下方法

   #!/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)

我也尝试添加

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

但结果总是这样

enter image description here

它也发生在 tkinter Entry 和 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)

还有什么我可以尝试使用标签、条目和文本的吗?

注意:我使用的是 Ubuntu 18.04 仿生

解决方法

您只需将此行设置为 Python 文件中的第一行(在您的代码之前),将您的编码设置为 UTF-8:# -- coding: UTF-8 -->

这是一个代码示例:

# -*- 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()

这是原始答案: Arabic text in TKinter

,

Tkinter 没有 bidi 支持(根据 tk 的源代码),这意味着像阿拉伯语这样的 RTL(从右到左)语言将显示不正确,有两个问题:

1- 字母将按相反顺序显示。

2- 字母未正确连接。

阿拉伯语在windows上能正确显示的原因是操作系统支持bidi,而在Linux中则不然

要在 linux 上解决这个问题,您可以使用 AwesomeTkinter 包,它可以为标签和条目添加双向支持(也在编辑时)

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()

输出:

enter image description here

注意:您可以通过 pip install awesometkinter

安装 awesometkinter