今天在使用Python的GUI平台wxPython时,写了一个只有打开、编辑、保存功能的简易笔记本,代码如下:
1 #coding:utf-8 2 import wx 3 4 def load(event): 5 f = open(FileName.GetValue()) 6 Contents.SetValue(f.read()) 7 f.close() 8 9 def save(event): 10 f = open(FileName.GetValue(), ‘w‘) 11 f.write(Contents.GetValue()) 12 f.close() 13 14 app = wx.App() 15 win = wx.Frame(None, title = "Simple Editor", size = (410, 335)) 16 bkg = wx.Panel(win) 17 18 LoadButton = wx.Button(bkg, label = "Open") 19 LoadButton.Bind(wx.EVT_BUTTON, load) 20 SaveButton = wx.Button(bkg, label = "Save") 21 SaveButton.Bind(wx.EVT_BUTTON, save) 22 FileName = wx.TextCtrl(bkg) 23 Contents = wx.TextCtrl(bkg, style = wx.TE_MULTILINE | wx.HSCROLL) 24 25 hbox = wx.BoxSizer() 26 hbox.Add(FileName, proportion = 1, flag = wx.EXPAND) 27 hbox.Add(LoadButton, proportion = 0, flag = wx.LEFT, border = 5) 28 hbox.Add(SaveButton, proportion = 0, flag = wx.LEFT, border = 5) 29 30 vbox = wx.BoxSizer(wx.VERTICAL) 31 vbox.Add(hbox, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5) 32 vbox.Add(Contents, proportion = 1, flag = wx.EXPAND | wx.LEFT | wx.BOTTOM | wx.RIGHT, 33 border = 5) 34 35 bkg.SetSizer(vbox) 36 win.Show() 37 38 app.MainLoop()
但是在使用过程中输入中文保存时,控制台报错:
Traceback (most recent call last):
File "D:\coding_file\python_file\TestPython\src\Test\test1.py", line 11, in save
f.write(Contents.GetValue())
UnicodeEncodeError: ‘ascii‘ codec can‘t encode characters in position 0-5: ordinal not in range(128)
由于Python默认使用不支持Unicode的中文编码,所以需要手动设置编码如utf-8,改动如下:
1 import wx, sys 2 reload(sys) 3 sys.setdefaultencoding(‘utf-8‘)
这样就可以输入中文并保存了,其中要特别注意 reload(sys) 这一行代码
reload()函数将以前导入过的模块再加载一次。重新加载(reload)包括最初导入模块时应用的分析过程和初始化过程。这样就允许在不退出解释器的情况下重新加载已更改的Python模块,从而改变字符集编码,问题解决。
时间: 2024-11-08 15:05:49