如何将UTF-8字符串从wx.TextCtrl传递给wx.ListCtrl
我在文本框里输入波罗的海字符,然后点击test1按钮时出现了错误。
"InicodeEncodeError: 'ascii' codec can't encode characters in position 0-3:
ordinal not in range(128)"
test2按钮运行得很好。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, (-1, -1), wx.Size(450, 300))
self.panel = wx.Panel(self)
self.input_area = wx.TextCtrl(self.panel, -1, '',(5,5),(200,200), style=wx.TE_MULTILINE)
self.output_list = wx.ListCtrl(self.panel, -1, (210,5), (200,200), style=wx.LC_REPORT)
self.output_list.InsertColumn(0, 'column')
self.output_list.SetColumnWidth(0, 100)
self.btn1 = wx.Button(self.panel, -1, 'test1', (5,220))
self.btn1.Bind(wx.EVT_BUTTON, self.OnTest1)
self.btn2 = wx.Button(self.panel, -1, 'test2', (100,220))
self.btn2.Bind(wx.EVT_BUTTON, self.OnTest2)
self.Centre()
def OnTest1(self, event):
self.output_list.InsertStringItem(0,str(self.input_area.GetValue()).decode('utf-8'))
def OnTest2(self, event):
self.output_list.InsertStringItem(0,"ąčęėįš".decode('utf-8'))
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'encoding')
frame.Show(True)
return True
app = MyApp(0)
app.MainLoop()
更新 1
我在两台Windows 7 Ultimate x64的电脑上试过这个代码。
这两台电脑都安装了python 2.7和wxPython2.8 win64 unicode,都是为了python 2.7。
在这两台机器上,我遇到的错误是一样的。
3 个回答
0
我无法重现这个问题……如果我尝试用瑞典字母“åäö”,似乎是可以正常工作的,还有使用“ąčęėįš”时也没问题,这是不是和地区设置有关呢?
0
你在用wxPython的unicode版本吗?你没有提到你的操作系统和其他系统信息。
0
把下面这段代码:
def OnTest1(self, event):
self.output_list.InsertStringItem(0,str(self.input_area.GetValue()).decode('utf-8'))
替换成:
def OnTest1(self, event):
self.output_list.InsertStringItem(0,self.input_area.GetValue())