在Python中将Unicode文件写入文本小部件

0 投票
1 回答
597 浏览
提问于 2025-04-17 20:45

我正在尝试使用Tkinter在文本小部件中打开一个Unicode文件,这是我的代码:

import codecs
def callback():
    matric_name = entry.get()
    with open(matric_name.rstrip('\n')+".txt", 'r') as content_file:
        content = content_file.read()   

    #myFile=file(matric_name.rstrip('\n')+".txt") # get a file handle
    # myText= myFile.read() # read the file to variable   
    # f = codecs.open(matric_name.rstrip('\n')+".txt", mode="r", encoding="iso-8859-1")
    # myText= f.read()
    # print myText
    #  myFile.close()

    print content
    mytext.insert(0.0,content)

代码运行得没问题,但在文本小部件中显示的内容不对。

小部件中的输出是 ÿþS

1 个回答

2

你需要用正确的编码来读取文件。可以使用 codecs 这个模块来做到这一点。一旦你正确地读取了数据,Tk 的文本组件就能接受 Unicode 字符串。下面是一个例子,它会把一个 Unicode 文件加载到文本组件中。你只需要把 Unicode 文本文件的名字作为命令行参数传入就可以了。

#!/usr/bin/python
import sys,codecs
from Tkinter import *

class App(Frame):
    def __init__(self, parent = None):
        Frame.__init__(self, parent)
        self.grid()
        self.text = Text(self)
        self.text.grid()

    def Load(self,filename):
        with codecs.open(filename, encoding='utf-16') as f:
            for line in f:
                self.text.insert('end', line)

def main(argv = None):
    if argv is None:
        argv = sys.argv
    app = App()
    if len(argv) > 1:
        app.after_idle(lambda: app.Load(argv[1]))
    app.mainloop()

if __name__=='__main__':
    sys.exit(main())

撰写回答