You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter文本框输入Unicode字符异常:输入ی变为ي问题咨询

问题原因与解决方案

输入的ی(波斯语 Yeh)自动变为ي(阿拉伯语 Alef Maksura),核心原因有两个:

  • Unicode字符归一化:Tkinter在部分环境下会自动对Unicode字符做归一化处理,将视觉相似的等价字符合并,导致波斯语Yeh被替换成阿拉伯语Alef Maksura。
  • 字体支持不足:如果当前Text组件使用的字体不支持波斯语字符,系统会自动 fallback 到仅支持阿拉伯语的字体,从而触发字符替换。

解决步骤

  • 指定支持波斯语的字体:创建Text组件时,明确设置支持波斯语的字体(比如Vazirmatn、Noto Sans Arabic,或系统自带的波斯语字体),确保字符能被正确渲染。
  • 阻止自动字符替换:在按键事件中直接捕获原始输入字符,避免Tkinter的自动转换逻辑。
  • 验证系统区域设置:确保系统语言区域设置包含波斯语,避免系统层面的字符映射干扰。

修改后的代码示例

import tkinter as tk
from tkinter import font

def submit_text():
    text_to_display = input_text.get("1.0", "end-1c")
    output_text.delete("1.0", tk.END)
    output_text.insert("1.0", text_to_display, "rtl_tag")

def on_keypress(event):
    # 捕获波斯语Yeh的原始输入,阻止默认替换
    if event.char == '\u06CC':
        input_text.insert(tk.INSERT, '\u06CC')
        return "break"
    # 维持RTL格式设置
    current_position = input_text.index(tk.INSERT)
    input_text.tag_configure("rtl_tag", justify='right')
    input_text.tag_add("rtl_tag", "1.0", "end")
    input_text.mark_set(tk.INSERT, current_position)

# 创建主窗口
root = tk.Tk()
root.title("波斯语文本输入")

# 设置支持波斯语的字体
persian_font = font.Font(family="Vazirmatn", size=12)

# 创建输入、输出文本框
input_text = tk.Text(root, font=persian_font, width=50, height=5)
input_text.pack(pady=10)
input_text.bind("<KeyPress>", on_keypress)

output_text = tk.Text(root, font=persian_font, width=50, height=5)
output_text.pack(pady=10)
output_text.tag_configure("rtl_tag", justify='right')

# 提交按钮
submit_btn = tk.Button(root, text="提交", command=submit_text)
submit_btn.pack(pady=5)

root.mainloop()

补充说明

  • 代码中使用的Vazirmatn是一款开源波斯语字体,若你的系统未安装,可替换为已安装的多语言字体(比如系统自带的波斯语字体)。
  • 通过捕获Unicode编码\u06CC(波斯语Yeh)并阻止默认处理,直接保留原始输入字符,避免被替换为阿拉伯语的\u064A。

内容的提问来源于stack exchange,提问作者Rana Zubair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 02:35:13