【问题标题】:problem with Cyrillic chars in tkinter listboxtkinter 列表框中的西里尔字符问题
【发布时间】:2021-05-12 12:40:43
【问题描述】:

我使用的是 Sublime Text 3,打印西里尔字符很好。 但是当相同的字符串被插入到 Tkinter 列表框时,该字符串仍然存在 不变。 字符串是:

st = '\u0418\u0441\u0442\u043e\u0440\u0438\u044f \u0414\u0440\u0435\u0432\u043d\u0435\u0438\u0306 \u0413\u0440\u0435\u0446\u0438\u0438 \u0421\u0435\u0440\u0433\u0435\u044f \u041a\u0430\u0440\u043f\u044e\u043a\u0430.mp4'

print(st)

История Древней Греции Сергея Карпюка.mp4

我已经尝试过这个构建系统:

{
    "shell_cmd": "python \"$file\"",
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",
    "env": {"PYTHONIOENCODING": "utf8"}
}

【问题讨论】:

    标签: python tkinter encoding sublimetext3


    【解决方案1】:

    通过运行下面的代码,我可以将字符串插入标签和列表框,没有任何问题。

    import tkinter as tk
    
    st = '\u0418\u0441\u0442\u043e\u0440\u0438\u044f \u0414\u0440\u0435\u0432\u043d\u0435\u0438\u0306 \u0413\u0440\u0435\u0446\u0438\u0438 \u0421\u0435\u0440\u0433\u0435\u044f \u041a\u0430\u0440\u043f\u044e\u043a\u0430.mp4'
    
    print(st)
    
    root = tk.Tk()
    label = tk.Label(root, text=st)
    label.pack()
    
    listbox = tk.Listbox(root)
    listbox.insert(0, st)
    listbox.pack(fill=tk.X, expand=True)
    
    root.mainloop()
    

    【讨论】:

    • 是的,这对我也有用。问题可能是我使用了从其中读取字符串的日志文件。我尝试将编码用作: with open(LOG, 'r', encoding="utf-8") as f: 但是这会截断数据,我没有得到所有的字符串。
    • 尝试open(LOG, 'rb')然后解码输出
    【解决方案2】:

    对我有用的解决方案是在通常模式下使用文件读取,而不是在 open(file) 命令中指定编码。 因为日志包含多种语言的文件名,所以我不得不使用 2 次尝试,除了 blocs。

    with open(LOG, 'r') as f:
        for line in f:
            for part in line:
                try:
                    # this fixes Cyrillic file names
                    part = part.encode('utf8').decode("unicode_escape")
                except Exception as e:
                    print(e)
                try:
                    # this fixes French, German file names
                    part = part.encode('latin1').decode('utf8')
                except Exception as e:
                    print(e)
        
                listboxMain.insert(tk.END,part)
    

    【讨论】:

    • pass 语句是多余的,所以我删除了它们。
    • @tripleee,是的,你是对的。一旦代码完全正常运行,我将保留 pass 或 print 语句。
    猜你喜欢
    • 2010-11-02
    • 1970-01-01
    • 2015-05-19
    • 2020-08-14
    • 2020-06-15
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 2019-07-23
    相关资源
    最近更新 更多