在使用wxpython编写保存和读取显示文件程序的时候,发现输入中文后无法保存,而在读取含有中文字符的文件时,也是无法读取并显示出来。代码如下:
def load(event):
file = open(filename.GetValue())
contents.SetValue(file.read())
file.close()
def save(event):
file = open(filename.GetValue(), 'w')
file.write(contents.GetValue())
file.close()
>>>
Traceback (most recent call last):
File "C:/Users/hyman/Desktop/btn.py", line 5, in load
contents.SetValue(file.read())
File "D:\Python27\lib\site-packages\wx-3.0-msw\wx\_core.py", line 13078, in SetValue
return _core_.TextEntryBase_SetValue(*args, **kwargs)
UnicodeDecodeError: 'gbk' codec can't decode bytes in position 52-53: illegal multibyte sequence
>>>
Traceback (most recent call last):
File "C:/Users/hyman/Desktop/btn.py", line 10, in save
file.write(contents.GetValue())
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
查阅资料并经过多次尝试,load()出问题是wx.TextCtrl中SetValue方法调用的问题。(SetValue():覆盖控件中的文本)
函数SetValue(str)应指明str的解码方式,即对str是utf8的字符串应设置成txtCtrl.SetValue(str.decode('utf8'))
而save()出问题则是wx.TextCtrl中GetValue方法调用的问题。(SetValue():返回控件中的字符串)
函数GetValue(str)应指明str的编码方式,即对str是utf8的字符串应设置成txtCtrl.GetValue(str.decode('utf8'))
def load(event):
file = open(filename.GetValue())
contents.SetValue(file.read().decode('utf-8'))
file.close()
def save(event):
file = open(filename.GetValue(), 'w')
file.write(contents.GetValue().encode('utf-8'))
file.close()
成功运行!
ps:python2.7.6版本+wxpython3.0 for windows
def load(event):
file = open(filename.GetValue())
contents.SetValue(file.read())
file.close()
def save(event):
file = open(filename.GetValue(), 'w')
file.write(contents.GetValue())
file.close()
>>>
Traceback (most recent call last):
File "C:/Users/hyman/Desktop/btn.py", line 5, in load
contents.SetValue(file.read())
File "D:\Python27\lib\site-packages\wx-3.0-msw\wx\_core.py", line 13078, in SetValue
return _core_.TextEntryBase_SetValue(*args, **kwargs)
UnicodeDecodeError: 'gbk' codec can't decode bytes in position 52-53: illegal multibyte sequence
>>>
Traceback (most recent call last):
File "C:/Users/hyman/Desktop/btn.py", line 10, in save
file.write(contents.GetValue())
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
查阅资料并经过多次尝试,load()出问题是wx.TextCtrl中SetValue方法调用的问题。(SetValue():覆盖控件中的文本)
函数SetValue(str)应指明str的解码方式,即对str是utf8的字符串应设置成txtCtrl.SetValue(str.decode('utf8'))
而save()出问题则是wx.TextCtrl中GetValue方法调用的问题。(SetValue():返回控件中的字符串)
函数GetValue(str)应指明str的编码方式,即对str是utf8的字符串应设置成txtCtrl.GetValue(str.decode('utf8'))
def load(event):
file = open(filename.GetValue())
contents.SetValue(file.read().decode('utf-8'))
file.close()
def save(event):
file = open(filename.GetValue(), 'w')
file.write(contents.GetValue().encode('utf-8'))
file.close()
成功运行!
ps:python2.7.6版本+wxpython3.0 for windows