python的桌面UI设计和处理貌似没有VB, C#等语言方便。今天查询了一些资料,发现用wxPython + wxFromBuilder是一个相对简单的方案。
1. 用pip下载最新的wxPython (我在下载的时候,发现pip默认的源下载wxPython连接不成功,切换到国内的源就成功)
2. 下载最新的的wxFromBuilder (注意下载与自己的python版本和系统版本对应的安装文件 ; 目前我下载的是wxFormBuilder_v3.5.1-rc1)
3. 参考这篇文章做了一个编辑器 ,这里不再赘述。 只补充一点, 添加事件的步骤如下,这里wxFromBuilder会自动生成Virtual event handlers,后面在具体使用UI的类(继承自wxFromBuilder生成的类)需重载这些event handlers。
具体的代码:
1:从wxFromBuilder中copy过来的代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/13 14:29
# @Author : PanCheng
# @Site :
# @File : MyFrame1.py
# @Software: PyCharm
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Jun 17 2015)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################
import wx
import wx.xrc
###########################################################################
## Class MyFrame1
###########################################################################
class MyFrame1(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"编辑器", pos=wx.DefaultPosition, size=wx.Size(494, 370),
style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
bSizer1 = wx.BoxSizer(wx.VERTICAL)
bSizer2 = wx.BoxSizer(wx.HORIZONTAL)
self.filename = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(250, 30), 0)
bSizer2.Add(self.filename, 0, wx.ALL, 5)
self.loadbutton = wx.Button(self, wx.ID_ANY, u"打开", wx.Point(-1, -1), wx.DefaultSize, 0)
bSizer2.Add(self.loadbutton, 0, wx.ALL, 5)
self.savebutton = wx.Button(self, wx.ID_ANY, u"保存", wx.DefaultPosition, wx.DefaultSize, 0)
bSizer2.Add(self.savebutton, 0, wx.ALL, 5)
bSizer1.Add(bSizer2, 1, wx.EXPAND, 5)
self.contents = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(480, 280),
0 | wx.HSCROLL | wx.VSCROLL)
bSizer1.Add(self.contents, 0, wx.ALL, 5)
self.SetSizer(bSizer1)
self.Layout()
self.Centre(wx.BOTH)
# Connect Events
self.loadbutton.Bind(wx.EVT_BUTTON, self.load)
self.savebutton.Bind(wx.EVT_BUTTON, self.save)
def __del__(self):
pass
# Virtual event handlers, overide them in your derived class
def load(self, event):
event.Skip()
def save(self, event):
event.Skip()
2:从具体处理UI事件和显示UI的代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/13 14:37
# @Author : PanCheng
# @Site :
# @File : ex22.py
# @Software: PyCharm
import wx
import sys
import os
import 编辑器.MyFrame1
class MyFrame(编辑器.MyFrame1.MyFrame1):
def load(self, event):
file = open(self.filename.GetValue())
self.contents.SetValue(file.read())
file.close()
def save(self, event):
file = open(self.filename.GetValue(), 'w')
file.write(self.contents.GetValue())
file.close()
if __name__ == "__main__":
app = wx.App()
main_win = MyFrame(None)
main_win.Show()
app.MainLoop()