本文实例讲述了python使用wxpython开发简单记事本的方法。分享给大家供大家参考。具体分析如下:
wxPython是Python编程语言的一个GUI工具箱。他使得Python程序员能够轻松的创建具有健壮、功能强大的图形用户界面的程序。它是Python语言对流行的wxWidgets跨平台GUI工具库的绑定。而wxWidgets是用C++语言写成的。
和Python语言与wxWidgetsGUI工具库一样,wxPython是开源软件。这意味着任何人都可以免费地使用它并且可以查看和修改它的源代码,或者贡献补丁,增加功能。
wxPython是跨平台的。这意味着同一个程序可以不经修改地在多种平台上运行。现今支持的平台有:32位微软Windows操作系统、大多数Unix或类Unix系统、苹果MacOS X。
下面使用wxpython编写一个简单的记事本程序,可以打开本地文件,编辑,保存。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#!/usr/bin/python
import wx
def OnOpen(event):
"""
Load a file into the textField.
"""
dialog = wx.FileDialog( None , 'Notepad' ,style = wx. OPEN )
if dialog.ShowModal() = = wx.ID_OK:
filename.SetValue(dialog.GetPath())
file = open (dialog.GetPath())
contents.SetValue( file .read())
file .close()
dialog.Destroy()
def OnSave(event):
"""
Save text into the orignal file.
"""
if filename.GetValue() = = '':
dialog = wx.FileDialog( None , 'Notepad' ,style = wx.SAVE)
if dialog.ShowModal() = = wx.ID_OK:
filename.SetValue(dialog.GetPath())
file = open (dialog.GetPath(), 'w' )
file .write(contents.GetValue())
file .close()
dialog.Destory()
else :
file = open (filename.GetValue(), 'w' )
file .write(contents.GetValue())
file .close()
app = wx.App()
win = wx.Frame( None , title = "Simple Editor" , size = ( 600 , 400 ))
bkg = wx.Panel(win)
# Define a 'load' button and its label,
# bind to an button event with a function 'load'
loadButton = wx.Button(bkg, label = 'Open' )
loadButton.Bind(wx.EVT_BUTTON, OnOpen)
# Define a 'save' button and its label,
# bind to an button event with a function 'save'
saveButton = wx.Button(bkg, label = 'Save' )
saveButton.Bind(wx.EVT_BUTTON, OnSave)
# Define a textBox for filename.
filename = wx.TextCtrl(bkg)
# Define a textBox for file contents.
contents = wx.TextCtrl(bkg, style = wx.TE_MULTILINE | wx.HSCROLL)
# Use sizer to set relative position of the components.
# Horizontal layout
hbox = wx.BoxSizer()
hbox.Add(filename, proportion = 1 , flag = wx.EXPAND)
hbox.Add(loadButton, proportion = 0 , flag = wx.LEFT, border = 5 )
hbox.Add(saveButton, proportion = 0 , flag = wx.LEFT, border = 5 )
# Vertical layout
vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(hbox, proportion = 0 , flag = wx.EXPAND | wx. ALL , border = 5 )
vbox.Add(contents, proportion = 1 ,
flag = wx.EXPAND | wx.LEFT | wx.BOTTOM | wx.RIGHT, border = 5 )
bkg.SetSizer(vbox)
win.Show()
app.MainLoop()
|
运行效果如下图所示:
这个例子是《Python基础教程》中的一个例子,并做了一些修改。虽然完成了基本的记事本功能,但是界面略显简单,而且代码也没有很好地遵循面向对象编程原则。
希望本文所述对大家的Python程序设计有所帮助。