wxpython无法保存和读取显示中文的解决

在使用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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值