区域设置,gbk和utf-8编码的坑¶
起因¶
main.py
# main.py
app=wx.App()
main_win=ui.TTSFrame(None)
main_win.Show()
app.MainLoop()
在ui文件中调用了以下代码
# ui.py
...
return time.strftime('%Y年%m月%d日 %H时%M分%S秒',time.localtime(xxxx))
...
然后就报错了
return time.strftime('%Y年%m月%d日 %H时%M分%S秒',time.localtime(a + vt))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: encoding error
接下来修改main.py文件看看哪里处理问题
import locale
print(1111)
print(locale.getlocale())
app=wx.App().InitLocale()
print(222)
print(locale.getlocale())
输出
1111
('Chinese (Simplified)_China', '936')
222
(None, None)
发现区域和编码都变None了。
后来翻看wxpython文档,看看app.MainLoop()做了什么,然后看到了一个这样的描述
InitLocale(self)¶Starting with version 3.8 on Windows, Python is now setting the locale to what is defined by the system as the default locale. This causes problems with wxWidgets which expects to be able to manage the locale via the wx.Locale class, so the locale will be reset here to be the default “C” locale settings.
If you have troubles from the default behavior of this method you can override it in a derived class to behave differently. Please report the problem you encountered.
翻译过来是
从Windows上的3.8版本开始,Python现在将区域设置为系统定义的默认区域设置。这会导致wxWidgets出现问题,它希望能够通过wx.Locale类管理区域设置,因此区域设置将在此处重置为默认的“C”区域设置。如果此方法的默认行为有问题,可以在派生类中重写它以使其行为不同。请报告您遇到的问题。
所以这就是原因。
解决方法¶
重写InitLocale方法
class MyApp(wx.App):
def __init__(self):
super().__init__()
def InitLocale(self):
pass # 使用python默认设置
app=MyApp()