【问题标题】:How to pass UTF-8 string from wx.TextCtrl to wx.ListCtrl如何将 UTF-8 字符串从 wx.TextCtrl 传递给 wx.ListCtrl
【发布时间】:2011-05-10 17:10:02
【问题描述】:

如果我在 textctrl 中输入波罗的海字符并单击按钮 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.7wxPython2.8 win64 unicode for python 2.7

在两台机器上我都有同样的错误。

【问题讨论】:

    标签: python utf-8 wxpython listctrl textctrl


    【解决方案1】:

    无法重现...如果我尝试使用瑞典字符“åäö”,它似乎也可以工作,在使用“ąčęėįš”语言环境问题时也是如此?

    【讨论】:

    • Ubuntu 9.10, Python 2.6.4 In [4]: wx.version() Out[4]: '2.8.10.1 (gtk2-unicode)'
    【解决方案2】:

    您使用的是 wxPython 的 unicode 版本吗?您没有提及您的平台和其他系统详细信息。

    【讨论】:

    • 我正在使用 wxPython2.8-win64-unicode-2.8.11.0-py27 和 python-2.7.amd64
    • 您的样本对我有用。 GTK -- 2.6.31-22-generic #68-Ubuntu SMP Tue Oct 26 16:37:17 UTC 2010 x86_64 GNU/Linux
    【解决方案3】:

    替换 def OnTest1(自我,事件): 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())
    

    【讨论】:

      猜你喜欢
      • 2012-03-06
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      相关资源
      最近更新 更多