[Tutor] Tkinter
Kent Johnson
kent37 at tds.net
Sat Aug 1 14:26:25 CEST 2009
On Sat, Aug 1, 2009 at 5:05 AM, Robert
Johansson<robert.johansson at math.umu.se> wrote:
> Dear all, I have a problem with Tkinter and swedish letters such as ä (or
> '\xe4'). Here’s a small code example that counts the number of occurrences
> of the letter ‘a’ is in a string given by the user:
>
>
>
> from Tkinter import *
>
>
>
> root=Tk()
>
>
>
> def callback():
>
> a=textLine.get()
>
> print a.count('a')
>
>
>
> textLine=Entry(root)
>
> textLine.pack(side=LEFT)
>
> searchButton=Button(root,command=callback,text='Search')
>
> searchButton.pack(side=RIGHT)
>
>
>
> root.mainloop()
>
>
>
> This works fine for strings containing all letters in my alphabet. However
> if I change it to count ä:s it works only for strings without our special
> letters (line 5: print a.count('ä')):
>
>
>
> in callback
>
> print a.count('ä')
>
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0:
> ordinal not in range(128)
The problem is that when you enter non-ascii characters into the
tkinter text box, it will return a unicode string. The count() method
then needs to convert it's argument from an encoded byte string to a
unicode string. It does this with the default (ascii) encoder and
fails.
Try passing a unicode string to count() like this:
print a.count(u'ä')
Kent
More information about the Tutor
mailing list