Foreign Character Problems In Python 2.5 and Tkinter

Juha S. jusa.sj at gmail.com
Sat Oct 13 04:01:31 EDT 2007


Hi,

I'm writing a small text editor type application with Python 2.5 and 
Tkinter. I'm using the Tk text widget for input and output, and the 
problem is that when I try to save its contents to a .txt file, any 
Scandinavian letters such as "äöå ÄÖÅ" are saved incorrectly and show up 
as a mess when I open the .txt file in Windows Notepad.

It seems that the characters will only get mixed if the user has typed 
them into the widget, but if the program has outputted them, they are 
saved correctly.

The function that is saving the file is as follows:

try:
file = open(self.currentSaveFile, 'w+')
file.write(self.text.get(0.0, END))
except IOError:
tkMessageBox.showwarning('Save File', 'An error occurred while trying to 
save \"' + self.currentSaveFile + '\"', parent=self.frame)
finally:
file.close()

Sometimes its output in the file is "äöå ÄÖÅ" for "äöå ÄÖÅ" and 
sometimes it gives me the error: "UnicodeEncodeError: 'ascii' codec 
can't encode characters in position 33-35: ordinal not in range(128)"


I have tried changing it to:

try:
file = codecs.open(savefilename, 'w+', 'utf-8', 'ignore')
file.write(unicode(self.text.get(0.0, END), 'utf-8', 'ignore'))
self.currentSaveFile = savefilename
except IOError:
tkMessageBox.showwarning('Save File', 'An error occurred while trying to 
save \"' + self.currentSaveFile + '\"', parent=self.frame)
finally:
file.close()

Which does save the user-typed characters correctly, but loses any 
newlines and "äöå" characters outputted by the program.

I have no idea how solve this problem, and would appreciate any help.



More information about the Python-list mailing list