Storm-Eyes
Storm-Eyes

Reputation: 821

UnicodeEncodeError while I try to fetch a Chinese String from Tkinter.Entry, in Python

An UnicodeEncodeError occurred while I tried to fetch a Chinese string from an Entry, an widget from 'tkinter' module. The operation system on which I am working is Windows 7 and the version of Python is Python3.4. The widget works well on English characters. Here is my program.

from tkinter import *

class LabelEntry(Frame):
    def __init__(self, parent, title, **config):
        Frame.__init__(self, parent, **config)
        self.title = title
        self.user_input = StringVar(parent)
        self.pack()
        self.makeWidgets()


    def makeWidgets(self):
        Label(self, text=self.title).pack(side=LEFT)
        ent = Entry(self, textvariable=self.user_input)
        ent.pack(side=RIGHT)
        ent.bind('<Return>', self.onReturnKey)

    def onReturnKey(self, event):
        print(self.user_input.get())

if __name__ == '__main__':
    tkroot = Tk()
    widget = LabelEntry(tkroot, 'corp_title')
    widget.mainloop()

Since I do not know how to solve to problem, I try to modify the program. This time, I do not use StringVar to save the string in the Entry, instead, I use Entry.get() to get the value directly. However, same exception occurs after I input a Chinese string. Here is the new program.

from tkinter import *

class LabelEntry(Frame):
    def __init__(self, parent, title, **config):
        Frame.__init__(self, parent, **config)
        self.title = title
        self.pack()
        self.makeWidgets()  

    def makeWidgets(self):
        Label(self, text=self.title).pack(side=LEFT)
        self.ent = Entry(self)
        self.ent.pack(side=RIGHT)
        self.ent.bind('<Return>', self.onReturnKey)

    def onReturnKey(self, event):
        print(self.ent.get())

if __name__ == '__main__':
    tkroot = Tk()
    widget = LabelEntry(tkroot, 'corp_title')
    widget.mainloop()

Please help me, thank you!

Upvotes: 1

Views: 680

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177620

Your console may not support, or be correctly configured to support, Chinese characters. Change:

print(self.user_input.get())

to:

print(ascii(self.user_input.get()))

You should see the correct Unicode codepoints displayed.

If you are on Windows, changing Control Panel's Region and Language, Administrative, Current language for non-Unicode programs to a Chinese locale will allow Chinese characters to print in the Windows console.

Better yet, display the text in a widget instead of printing to the console.

Upvotes: 2

Related Questions