2017-08-03 16 views
0

我正在使用區域語言文本編輯器,它從文本小部件中獲取區域Unicode字符(我使用的腳本是Gurmukhi和Unicode兼容字體是Raavi),並將其打印在終端上屏幕。文本小部件不顯示Unicode字符

現在問題出現了,當我複製並粘貼一些字符串到文本小部件時,它會轉換成如圖所示的框,但它會在終端窗口上打印完美的字符串。

雖然我試過encodingdecoding功能從codecs,但是,這也是徒勞。

我找不到任何與Tkinter中Text插件的Unicode輸入機制有關的答案。

如何在文本小部件中顯示完美的unicode字符串?

這裏是我的代碼:

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

下面是輸入和輸出:

Input and Output

+0

你確定你正在使用支持Unicode的「Raavi」字體?使用字符串不是配置字體的正確方法。也許這個小部件會回落到一個不支持你的角色的默認字體。 –

+0

我試圖使用給定的解決方案[這裏](https://stackoverflow.com/questions/31918073/tkinter-how-to-set-font-for-text)來處理輸入字體的Unicode文本。據我所知,Python使用編解碼器處理Unicode文本,但其編碼和解碼功能不起作用。 –

+0

要顯示一個字符,字體必須有一個字形。它可以100%正確編碼或解碼,但如果字體不支持字符,那麼小部件將不可能正確顯示字符。你的第一步是確保你使用的是合適的字體。 –

回答

1

我們如何可以顯示文本組件完美unicode字符串ਸਤਵਿੰਦਰ?

假如你安裝了正確的字體,你的代碼應該可以工作。我已經減少你的代碼到一個更小例子:

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

在我的系統中,這會導致以下:

screenshot of tkinter window

當我打印的customFont.actual()結果我得到以下(我沒有安裝「Ravii」字體,因此tkinter會替代後備字體,這可能與您的系統不同):

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

T Ø看到所有的字體系列的列表,你Tkinter的安裝將認識到,運行此代碼:

from tkinter import font, Tk 

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

我試圖在我的系統上運行您的給定代碼,但它顯示的是相同的框而不是文本。我不知道爲什麼? –

+0

我得到以下結果:{'underline':0,'weight':'normal','family':'fixed','slant':'roman','size':17,'overstrike':0} –

+2

@ programmer_123:這意味着你沒有正確指定字體,所以tkinter正在回落到默認值。它告訴你,儘管你要求什麼,但實際上它使用的是一個名爲「fixed」的字體家族。 –