1.两个子类,重定向输出
运行效果:
============================================
代码部分:
============================================
#!/usr/bin/env python
#coding=utf-8
import wx
import sys
class Frame(wx.Frame):
def __init__(self, parent, id, title,size):
print "Frame __init__"
wx.Frame.__init__(self, parent, id, title,size)
class App(wx.App):
def __init__(self, redirect=True, filename=None):
print "App __init__"
wx.App.__init__(self, redirect, filename)
def OnInit(self):
print "OnInit" #输出到stdout
self.frame = Frame(parent=None, id=-1, title='Startup',size=(400,100)) #创建框架
self.frame.Show()
self.SetTopWindow(self.frame)
print sys.stderr, "A pretend error message" #输出到stderr
return True
def OnExit(self):
print "OnExit"
if __name__ == '__main__':
app = App(redirect=True) #1 文本重定向从这开始
print "before MainLoop"
app.MainLoop() #2 进入主事件循环
print "after MainLoop"
2.单个图像建立在frame上
运行效果:
============================================
代码部分:
============================================
#!/usr/bin/env python
"""Hello, wxPython! program."""
import wx
class Frame(wx.Frame): #2 wx.Frame子类
"""Frame class that displays an p_w_picpath."""
def __init__(self, p_w_picpath, parent=None, id=-1,
pos=wx.DefaultPosition,
title='Hello, wxPython!'): #3图像参数
"""Create a Frame instance and display p_w_picpath."""
#4 显示图像
temp = p_w_picpath.ConvertToBitmap()
size = temp.GetWidth(), temp.GetHeight()
wx.Frame.__init__(self, parent, id, title, pos, size)
self.bmp = wx.StaticBitmap(parent=self, bitmap=temp)
class App(wx.App): #5 wx.App子类
"""Application class."""
def OnInit(self):
#6 图像处理
p_w_picpath = wx.Image('pop.jpg', wx.BITMAP_TYPE_JPEG)
self.frame = Frame(p_w_picpath)
self.frame.Show()
self.SetTopWindow(self.frame)
return True
def main(): #7
app = App()
app.MainLoop()
if __name__ == '__main__':
main()
3.多个图像(wx.FlexGridSizer)建立在panel上
运行效果:
============================================
代码部分:
============================================
#coding=utf-8
import wx
filenames = ["D:\pop.jpg", "D:\pop.png" ]
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Loading Images")
p = wx.Panel(self)
fgs = wx.FlexGridSizer(cols=2, hgap=10, vgap=10)
for name in filenames:
#1 从文件载入图像
img1 = wx.Image(name, wx.BITMAP_TYPE_ANY)
# Scale the oiginal to another wx.Image
w = img1.GetWidth()
h = img1.GetHeight()
img2 = img1.Scale(w/2, h/2)#2 缩小图像
#3 转换它们为静态位图部件
sb1 = wx.StaticBitmap(p, -1, wx.BitmapFromImage(img1))
sb2 = wx.StaticBitmap(p, -1, wx.BitmapFromImage(img2))
# and put them into the sizer
fgs.Add(sb1)
fgs.Add(sb2)
p.SetSizerAndFit(fgs)
self.Fit()
app = wx.PySimpleApp()
frm = TestFrame()
frm.Show()
app.MainLoop()
3.工具栏
运行效果:
============================================
代码部分:
============================================
#!/usr/bin/env python
# FileName: toolbar.py
import wx
import wx.py.p_w_picpaths as p_w_picpaths
class MyToolBar( wx.Frame ):
def __init__( self, parent, ID, title ):
wx.Frame.__init__( self, parent, ID, title, wx.DefaultPosition, wx.Size( 350, 250 ) )
vbox = wx.BoxSizer( wx.VERTICAL )
toolbar = wx.ToolBar( self, -1, style=wx.TB_HORIZONTAL | wx.NO_BORDER )
toolbar.AddSimpleTool( 1, p_w_picpaths.getPyBitmap(), 'New', '' )
toolbar.AddSimpleTool( 2, p_w_picpaths.getPyBitmap(), 'Opne', '' )
toolbar.AddSimpleTool( 3, p_w_picpaths.getPyBitmap(), 'Save', '' )
toolbar.AddSeparator()
toolbar.AddSimpleTool( 4, p_w_picpaths.getPyBitmap(), 'Exit', '' )
toolbar.Realize()
vbox.Add( toolbar, 0, border=5 )
self.SetSizer( vbox )
self.statusbar = self.CreateStatusBar()
self.Centre()
wx.EVT_TOOL( self, 1, self.OnNew )
wx.EVT_TOOL( self, 2, self.OnOpen )
wx.EVT_TOOL( self, 3, self.OnSave )
wx.EVT_TOOL( self, 4, self.OnExit )
def OnNew( self, event ):
self.statusbar.SetStatusText( 'New Command' )
def OnOpen( self, event ):
self.statusbar.SetStatusText( 'Open Command' )
def OnSave( self, event ):
self.statusbar.SetStatusText( 'Save Command' )
def OnExit( self, event ):
self.Close()
class MyApp( wx.App ):
def OnInit(self):
frame = MyToolBar( None, -1, ' toolbar.py' )
frame.Show( True )
return True
app = MyApp( 0 )
app.MainLoop()
4.添加一个工具栏到sketch应用程序
运行效果:
============================================
代码部分:
============================================
import wx
from example1 import SketchWindow
import wx.py.p_w_picpaths as p_w_picpaths
#img1 = ["D:\book.png" ]
class SketchFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Sketch Frame",
size=(800,600))
self.sketch = SketchWindow(self, -1)
self.sketch.Bind(wx.EVT_MOTION, self.OnSketchMotion)
self.initStatusBar() #1 这里因重构有点变化
self.createMenuBar()
self.createToolBar()
#self.createSimpleTool()
def initStatusBar(self):
self.statusbar = self.CreateStatusBar()
self.statusbar.SetFieldsCount(3)
self.statusbar.SetStatusWidths([-1, -2,-3])
def OnSketchMotion(self, event):
self.statusbar.SetStatusText("Pos: %s" %
str(event.GetPositionTuple()), 0)
self.statusbar.SetStatusText("Current Pts: %s" %
len(self.sketch.curLine), 1)
self.statusbar.SetStatusText("Line Count: %s" %
len(self.sketch.lines), 2)
event.Skip()
def menuData(self): #2 菜单数据
return [(" 菜单", (
(" New", "New Sketch file", self.OnNew),
(" Open", "Open sketch file", self.OnOpen),
(" Save", "Save sketch file", self.OnSave),
("", "", ""),
("abc ", (
("dragon1 ", "", self.OnColor,
wx.ITEM_RADIO),
("dragon2 ", "", self.OnColor,
wx.ITEM_RADIO),
("dragon3 ", "", self.OnColor,
wx.ITEM_RADIO),
("dragon4 ", "", self.OnColor,
wx.ITEM_RADIO))),
("", "", ""),
(" Quit", "Quit", self.OnCloseWindow)))]
def createMenuBar(self):
menuBar = wx.MenuBar()
for eachMenuData in self.menuData():
menuLabel = eachMenuData[0]
menuItems = eachMenuData[1]
menuBar.Append(self.createMenu(menuItems), menuLabel)
self.SetMenuBar(menuBar)
def createMenu(self, menuData):
menu = wx.Menu()
#3 创建子菜单
for eachItem in menuData:
if len(eachItem) == 2:
label = eachItem[0]
subMenu = self.createMenu(eachItem[1])
menu.AppendMenu(wx.NewId(), label, subMenu)
else:
self.createMenuItem(menu, *eachItem)
return menu
def createMenuItem(self, menu, label, status, handler,
kind=wx.ITEM_NORMAL):
if not label:
menu.AppendSeparator()
return
menuItem = menu.Append(-1, label, status, kind)#4 使用kind创建菜单项
self.Bind(wx.EVT_MENU, handler, menuItem)
def OnNew(self, event): pass
def OnOpen(self, event): pass
def OnSave(self, event): pass
def OnColor(self, event):#5 处理颜色的改变
menubar = self.GetMenuBar()
itemId = event.GetId()
item = menubar.FindItemById(itemId)
color = item.GetLabel()
self.sketch.SetColor(color)
def OnCloseWindow(self, event):
self.Destroy()
def createToolBar(self):#1创建工具栏
toolbar = self.CreateToolBar()
for each in self.toolbarData():
self.createSimpleTool(toolbar, *each)
toolbar.AddSeparator()
for each in self.toolbarColorData():
self.createColorTool(toolbar, each)
toolbar.Realize()#2 显现工具栏
def createSimpleTool(self, toolbar, label, filename,help, handler):#3 创建常规工具
if not label:
toolbar.AddSeparator()
return
bmp = p_w_picpaths.getPyBitmap()
tool = toolbar.AddSimpleTool(-1, bmp, label, help)
self.Bind(wx.EVT_MENU, handler, tool)
def toolbarData(self):
return (("New", "a", "Create new sketch",self.OnNew),
("", "", "", ""),
("Open", "b", "Open existing sketch",self.OnOpen),
("Save", "c", "Save existing sketch",self.OnSave))
def createColorTool(self, toolbar, color):#4 创建颜色工具
bmp = self.MakeBitmap(color)
newId = wx.NewId()
tool = toolbar.AddRadioTool(-1, bmp, shortHelp=color)
self.Bind(wx.EVT_MENU, self.OnColor, tool)
def MakeBitmap(self, color):#5 创建纯色的位图
bmp = wx.EmptyBitmap(16, 15)
dc = wx.MemoryDC()
dc.SelectObject(bmp)
dc.SetBackground(wx.Brush(color))
dc.Clear()
dc.SelectObject(wx.NullBitmap)
return bmp
def toolbarColorData(self):
return ("Black", "Red", "Green", "Blue")
def OnColor(self, event):#6 改变画笔颜色以响应工具栏的敲击
menubar = self.GetMenuBar()
itemId = event.GetId()
item = menubar.FindItemById(itemId)
if not item:
toolbar = self.GetToolBar()
item = toolbar.FindById(itemId)
color = item.GetShortHelp()
else:
color = item.GetLabel()
self.sketch.SetColor(color)
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = SketchFrame(None)
frame.Show(True)
app.MainLoop()
附件:example1
#coding=utf-8
import wx
class SketchWindow(wx.Window):
def __init__(self, parent, ID):
wx.Window.__init__(self, parent, ID)
self.SetBackgroundColour("White")
self.color = "Black"
self.thickness = 1
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)#1 创建一个wx.Pen对象
self.lines = []
self.curLine = []
self.pos = (0, 0)
self.InitBuffer()
#2 连接事件
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
self.Bind(wx.EVT_MOTION, self.OnMotion)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_IDLE, self.OnIdle)
self.Bind(wx.EVT_PAINT, self.OnPaint)
def InitBuffer(self):
size = self.GetClientSize()
#3 创建一个缓存的设备上下文
self.buffer = wx.EmptyBitmap(size.width, size.height)
dc = wx.BufferedDC(None, self.buffer)
#4 使用设备上下文
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
self.DrawLines(dc)
self.reInitBuffer = False
def GetLinesData(self):
return self.lines[:]
def SetLinesData(self, lines):
self.lines = lines[:]
self.InitBuffer()
self.Refresh()
def OnLeftDown(self, event):
self.curLine = []
self.pos = event.GetPositionTuple()#5 得到鼠标的位置
self.CaptureMouse()#6 捕获鼠标
def OnLeftUp(self, event):
if self.HasCapture():
self.lines.append((self.color,
self.thickness,
self.curLine))
self.curLine = []
self.ReleaseMouse()#7 释放鼠标
def OnMotion(self, event):
if event.Dragging() and event.LeftIsDown():#8 确定是否在拖动
dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)#9 创建另一个缓存的上下文
self.drawMotion(dc, event)
event.Skip()
#10 绘画到设备上下文
def drawMotion(self, dc, event):
dc.SetPen(self.pen)
newPos = event.GetPositionTuple()
coords = self.pos + newPos
self.curLine.append(coords)
dc.DrawLine(*coords)
self.pos = newPos
def OnSize(self, event):
self.reInitBuffer = True #11 处理一个resize事件
def OnIdle(self, event):#12 空闲时的处理
if self.reInitBuffer:
self.InitBuffer()
self.Refresh(False)
def OnPaint(self, event):
dc = wx.BufferedPaintDC(self, self.buffer)#13 处理一个paint(描绘)请求
#14 绘制所有的线条
def DrawLines(self, dc):
for colour, thickness, line in self.lines:
pen = wx.Pen(colour, thickness, wx.SOLID)
dc.SetPen(pen)
for coords in line:
dc.DrawLine(*coords)
def SetColor(self, color):
self.color = color
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)
def SetThickness(self, num):
self.thickness = num
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)
class SketchFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Sketch Frame",
size=(800,600))
self.sketch = SketchWindow(self, -1)
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = SketchFrame(None)
frame.Show(True)
app.MainLoop()
5.wxPython实现折叠面板
运行效果:
============================================
代码部分:
============================================
#! /usr/bin/env python
#coding=utf-8
import wx
class MyFrame(wx.Frame):
def __init__(self, parent=None, title=u'折叠与展开'):
wx.Frame.__init__(self, parent, -1, title=title)
self.panel = wx.Panel(self, style=wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN | wx.FULL_REPAINT_ON_RESIZE)
#增加一些控件:用户名密码部分,并使用GridBagSizer来管理这些控件
self.label1=wx.StaticText(self.panel,-1,label=u'用户名:')
self.label2=wx.StaticText(self.panel,-1,label=u'密 码:')
self.userText=wx.TextCtrl(self.panel,-1,size=(200,25))
self.passText=wx.TextCtrl(self.panel,-1,size=(200,25))
self.rempassCheck=wx.CheckBox(self.panel,-1,label=u'记住密码')
self.autologCheck=wx.CheckBox(self.panel,-1,label=u'自动登录')
self.gbsizer1=wx.GridBagSizer(hgap=10, vgap=10)
self.gbsizer1.Add(self.label1,pos=(0,0),span=(1,1),flag=wx.ALIGN_RIGHT|wx.ALIGN_CENTRE_VERTICAL)
self.gbsizer1.Add(self.userText,pos=(0,1),span=(1,1),flag=wx.EXPAND)
self.gbsizer1.Add(self.label2,pos=(1,0),span=(1,1),flag=wx.ALIGN_RIGHT|wx.ALIGN_CENTRE_VERTICAL)
self.gbsizer1.Add(self.passText,pos=(1,1),span=(1,1),flag=wx.EXPAND)
self.gbsizer1.Add(self.rempassCheck,pos=(2,0),span=(1,1),flag=wx.ALIGN_RIGHT|wx.ALIGN_CENTRE_VERTICAL)
self.gbsizer1.Add(self.autologCheck,pos=(2,1),span=(1,1),flag=wx.ALIGN_CENTER|wx.ALIGN_CENTRE_VERTICAL)
#增加一些控件:服务器设置部分,并使用GridBagSizer来管理这些控件,
#然后再使用StaticBoxSizer管理GridBagSizer
self.label3=wx.StaticText(self.panel,-1,label=u'地址:')
self.label4=wx.StaticText(self.panel,-1,label=u'端口:')
self.ipadText=wx.TextCtrl(self.panel,-1,size=(170,25))
self.portText=wx.TextCtrl(self.panel,-1,size=(170,25))
self.proxyBtn=wx.Button(self.panel,-1,label=u'代理\n设置')
self.gbsizer2=wx.GridBagSizer(hgap=10,vgap=10)
self.gbsizer2.Add(self.label3,pos=(0,0),span=(1,1),flag=wx.ALIGN_RIGHT|wx.ALIGN_CENTRE_VERTICAL)
self.gbsizer2.Add(self.ipadText,pos=(0,1),span=(1,1),flag=wx.EXPAND)
self.gbsizer2.Add(self.proxyBtn,pos=(0,2),span=(2,1),flag=wx.EXPAND)
self.gbsizer2.Add(self.label4,pos=(1,0),span=(1,1),flag=wx.ALIGN_RIGHT|wx.ALIGN_CENTRE_VERTICAL)
self.gbsizer2.Add(self.portText,pos=(1,1),span=(1,1),flag=wx.EXPAND)
sbox=wx.StaticBox(self.panel,-1,label=u'服务器')
self.sbsizer=wx.StaticBoxSizer(sbox,wx.VERTICAL)
self.sbsizer.Add(self.gbsizer2,proportion=0,flag=wx.EXPAND,border=10)
#增加一些控件:最下方的按钮,并使用水平方向的BoxSizer来管理这些控件
self.setserverBtn=wx.Button(self.panel,-1,label=u'服务器设置↓')
self.loginBtn=wx.Button(self.panel,-1,label=u'登录')
self.cancelBtn=wx.Button(self.panel,-1,label=u'取消')
self.bsizer=wx.BoxSizer(wx.HORIZONTAL)
self.bsizer.Add(self.setserverBtn,1,flag=wx.EXPAND)
self.bsizer.Add(self.loginBtn)
self.bsizer.Add(self.cancelBtn)
#给"服务器设置"按钮绑定事件处理器
self.Bind(wx.EVT_BUTTON, self.OnTouch, self.setserverBtn)
#增加BoxSizer,管理用户名密码部分的gbsizer1,
#服务器设置部分的sbsizer,以及最下方的bsizer
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.gbsizer1, 0, wx.EXPAND, 20)
self.sizer.Add(self.sbsizer, 0, wx.EXPAND, 20)
self.sizer.Add(self.bsizer, 0, wx.EXPAND, 20)
self.isShown = False #用这个变量指示当前是否已将控件隐藏
self.sizer.Hide(self.sbsizer) #将控件隐藏
self.SetClientSize((330,118)) #更改面板尺寸
self.panel.SetSizerAndFit(self.sizer)
self.sizer.SetSizeHints(self.panel)
def OnTouch(self, event):
if self.isShown: #如果当前控件已显示
self.setserverBtn.SetLabel(u'服务器设置↓') #更新按钮标签
self.sizer.Hide(self.sbsizer) #隐藏服务器设置部分
self.isShown = False #服务器设置部分当前已隐藏
self.SetClientSize((330,118)) #更新面板尺寸
else:
self.sizer.Show(self.sbsizer) #如果当前控件已隐藏
self.setserverBtn.SetLabel(u'服务器设置↑') #更新按钮标签
self.isShown = True #服务器设置部分当前已显示
self.SetClientSize((330,200)) #更新面板尺寸
self.sizer.Layout() #关键所在,强制sizer重新计算并布局sizer中的控件
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyFrame(None)
frame.Show(True)
app.MainLoop()
6.wxPython构建小型管理系统
运行效果:
============================================
代码部分:
============================================
#coding:gbk
import wx
class TestTB(wx.Treebook):
def __init__(self, parent, id):
wx.Treebook.__init__(self, parent, id, style=wx.BK_DEFAULT)
idGenerator=self.getNextID(50)#实例化生成器
first=True
panlist=self.getPageList()#得到目录列表
for x in panlist:
for k,v in x.items():
win=self.makeDemoPanel()#父页面
self.AddPage(win,k,p_w_picpathId=idGenerator.next())
if first:
first=False
else:
for sub in v:
win=sub[1]
self.AddSubPage(win,sub[0],p_w_picpathId=idGenerator.next())
#由上面的例子可以看出,父/子页面关系完全由添加的顺序而定
#即你AddPage后AddSubPage,一定是刚才这个Page所对应的菜单的子菜单的页面,
#所以看不到设“父目录”的代码
self.Bind(wx.EVT_TREEBOOK_PAGE_CHANGED, self.OnPageChanged)
self.Bind(wx.EVT_TREEBOOK_PAGE_CHANGING, self.OnPageChanging)
# This is a workaround for a sizing bug on Mac...
wx.FutureCall(100, self.AdjustSize)
def getNextID(self,count):
'''一个ID生成器'''
imID = 0
while True:
yield imID
imID += 1
if imID == count:
imID = 0
def AdjustSize(self):
self.GetTreeCtrl().InvalidateBestSize()
self.SendSizeEvent()
def makeDemoPanel(self,type=None):
p = wx.Panel(self, -1)#子窗体的容器
win=wx.Panel(p,-1)#子窗体容器包含的页面,此处我还是用了一个panel
wx.StaticText(win,-1,type or "parnet")#此两句,在项目中用的时候应该包装出去,因为你的窗体可能非常复杂,而不是像我现在演示的这样仅仅只有一个Label
p.win = win
def OnCPSize(evt, win=win):
win.SetPosition((0,0))
win.SetSize(evt.GetSize())
p.Bind(wx.EVT_SIZE, OnCPSize)
return p
def getPageList(self):
'''我是以父目录为键名,子目录List为键值来保存本示例的菜单数据
同时,子目录列表的结构为(子目录名,对应窗体对象)的元组,这样每次生成tree的子目录的时候,可以直接把窗体对象AddSubPage进去
'''
return [
{'根节点 ':[]},
{'一级目录1':[('二级目录一',self.makeDemoPanel('内页1')),('二级目录二',self.makeDemoPanel('内页2')),('二级目录三',self.makeDemoPanel('内页3')),('二级目录四',self.makeDemoPanel('内页4')),]},
{'一级目录2':[('二级目录一',self.makeDemoPanel('内页1')),('二级目录二',self.makeDemoPanel('内页2')),('二级目录三',self.makeDemoPanel('内页3')),('二级目录四',self.makeDemoPanel('内页4')),]},
{'一级目录3':[('二级目录一',self.makeDemoPanel('内页1')),('二级目录二',self.makeDemoPanel('内页2')),('二级目录三',self.makeDemoPanel('内页3')),('二级目录四',self.makeDemoPanel('内页4')),]},
{'一级目录4':[('二级目录一',self.makeDemoPanel('内页1')),('二级目录二',self.makeDemoPanel('内页2')),('二级目录三',self.makeDemoPanel('内页3')),('二级目录四',self.makeDemoPanel('内页4')),]},
{'一级目录5':[('二级目录一',self.makeDemoPanel('内页1')),('二级目录二',self.makeDemoPanel('内页2')),('二级目录三',self.makeDemoPanel('内页3')),('二级目录四',self.makeDemoPanel('内页4')),]},
{'一级目录6':[('二级目录一',self.makeDemoPanel('内页1')),('二级目录二',self.makeDemoPanel('内页2')),('二级目录三',self.makeDemoPanel('内页3')),('二级目录四',self.makeDemoPanel('内页4')),]},
{'一级目录7':[('二级目录一',self.makeDemoPanel('内页1')),('二级目录二',self.makeDemoPanel('内页2')),('二级目录三',self.makeDemoPanel('内页3')),('二级目录四',self.makeDemoPanel('内页4')),]},
]
def OnPageChanged(self, event):
'''演示捕捉页面切换事件'''
old = event.GetOldSelection()
new = event.GetSelection()
sel = self.GetSelection()
print 'OnPageChanged, old:%d, new:%d, sel:%d\n' % (old, new, sel)
event.Skip()
def OnPageChanging(self, event):
'''演示捕捉页面切换事件'''
old = event.GetOldSelection()
new = event.GetSelection()
sel = self.GetSelection()
print 'OnPageChanging, old:%d, new:%d, sel:%d\n' % (old, new, sel)
event.Skip()
def main():
app=wx.App()#实际化应用
frame=wx.Frame(None,-1,"my tree book demo")#实例化窗体
def onExitApp(evt):
'''退出的方法'''
frame.Close(True)
menuBar=wx.MenuBar()#顺便生成一个菜单,含有“退出”功能
menu=wx.Menu()
item=menu.Append(-1,"Exit\tCtrl-Q","Exit")
frame.Bind(wx.EVT_MENU,onExitApp,item)
frame.SetMenuBar(menuBar)
menuBar.Append(menu,"&File")
win=TestTB(frame,-1)#生成TreeBook
if win:
frame.SetSize((800,600))
frame.Centre()
frame.Show()
win.SetFocus()
frame.window=win#设置TreeBook控件为主窗体对象(其实我还是不明白frame对象的window属性有什么特权)
else:
frame.Destory()
app.MainLoop()#进入主消息循环
if __name__ == '__main__':
main()
7.自动搜索"computer"/登录人人网
运行效果:
============================================
代码部分:
============================================
搜索“computer”
# -*- coding: utf-8 -*-
import ie
url = "http://ieeexplore.ieee.org/xpl/periodicals.jsp"
myie = ie.NewIE(url)
ie.Visible(myie)
mybody = ie.GetBody(myie)
input_ids=ie.GetNodes(mybody,"input")
input_id_topsearch = ie.NodeByAttr(input_ids, "id", "browse_keyword")
input_id_topsearch.value = "computer"
div_ids=ie.GetNodes(mybody,"div")
div_browser_title_hdr = ie.NodeByAttr(div_ids, "id", "browse-title-hdr")
div_browser_input = ie.GetNodes(div_browser_title_hdr, "input")
input_id_search = ie.NodeByAttr(div_browser_input, "type", "p_w_picpath")
input_id_search.click();
登录人人网
# -*- coding:utf -*-
import getpass
import ie
url="http://renren.com/"
myie=ie.NewIE(url)
ie.Visible(myie)
mybody=ie.GetBody(myie)
input_ids=ie.GetNodes(mybody,"input")
input_id_email=ie.NodeByAttr(input_ids,"id","email")
input_id_email.value=""
input_id_psd=ie.NodeByAttr(input_ids,"id","password")
input_id_psd.value=getpass.getpass()
input_id_login=ie.NodeByAttr(input_ids,"id","login")
input_id_login.click()
附件:ie.py
# -*- coding:utf-8 -*-
import time
from win32com.client import DispatchEx
def ExistIE(url):
ShellWindowsCLSID = '{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'
ies=DispatchEx(ShellWindowsCLSID)
if len(ies)==0:
return None
for ie in ies:
if ie.LocationURL==url:
return ie
return None
def NewIE(url):
ie=DispatchEx("InternetExplorer.Application")
ie.Navigate(url)
return ie
def openIE(url):
"""
>>> myie = ie.NewIE()
"""
ie=ExistIE(url)
if ie==None:
ie=NewIE(url)
return ie
def WaitIE(ie):
while ie.Busy:
time.sleep(1)
def Visible(ie):
ie.Visible=1-ie.Visible
def GetBody(ie):
WaitIE(ie)
return ie.Document.body
def GetNodes(parentNode,tag):
"""
>>> coldiv=GetNodes(body,"div")
"""
childNodes=[]
for childNode in parentNode.getElementsByTagName(tag):
childNodes.append(childNode)
return childNodes
def NodeByAttr(Nodes,nodeattr,nodeval):
"""
>>> div_id_editor=NodeByAttr(coldiv,"id","editor_ifr")
"""
for node in Nodes:
if str(node.getAttribute(nodeattr))==nodeval:
return node
return None
def SetNode(node,val):
node.innerHTML=val
if __name__=="__main__":
url="about:blank"
myie=NewIE(url)
Visible(myie)
mybody=GetBody(myie)
SetNode(mybody,"<div>Genius</div>"*3)
coldiv=GetNodes(mybody,"div")
SetNode(coldiv[0],"<p>Hello</p>"*10)
coldiv[0].SetAttribute("id","test")
div_id_test=ie.NodeByAttr(coldiv,"id","test")
div_p=GetNodes(div_id_test,"p")
for div_per_p in div_p:
print div_per_p.innerHTML
8.画板
运行效果:
============================================
代码部分:
============================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Function:绘图
Input:NONE
Output: NONE
author: socrates
blog:http://www.cnblogs.com/dyx1024/
date:2012-07-13
'''
import wx
class PaintWindow(wx.Window):
def __init__(self, parent, id):
wx.Window.__init__(self, parent, id)
self.SetBackgroundColour("Red")
self.color = "Green"
self.thickness = 10
#创建一个画笔
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)
self.lines = []
self.curLine = []
self.pos = (0, 0)
self.InitBuffer()
#连接事件
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
self.Bind(wx.EVT_MOTION, self.OnMotion)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_IDLE, self.OnIdle)
self.Bind(wx.EVT_PAINT, self.OnPaint)
def InitBuffer(self):
size = self.GetClientSize()
#创建缓存的设备上下文
self.buffer = wx.EmptyBitmap(size.width, size.height)
dc = wx.BufferedDC(None, self.buffer)
#使用设备上下文
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
self.DrawLines(dc)
self.reInitBuffer = False
def GetLinesData(self):
return self.lines[:]
def SetLinesData(self, lines):
self.lines = lines[:]
self.InitBuffer()
self.Refresh()
def OnLeftDown(self, event):
self.curLine = []
#获取鼠标位置
self.pos = event.GetPositionTuple()
self.CaptureMouse()
def OnLeftUp(self, event):
if self.HasCapture():
self.lines.append((self.color,
self.thickness,
self.curLine))
self.curLine = []
self.ReleaseMouse()
def OnMotion(self, event):
if event.Dragging() and event.LeftIsDown():
dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)
self.drawMotion(dc, event)
event.Skip()
def drawMotion(self, dc, event):
dc.SetPen(self.pen)
newPos = event.GetPositionTuple()
coords = self.pos + newPos
self.curLine.append(coords)
dc.DrawLine(*coords)
self.pos = newPos
def OnSize(self, event):
self.reInitBuffer = True
def OnIdle(self, event):
if self.reInitBuffer:
self.InitBuffer()
self.Refresh(False)
def OnPaint(self, event):
dc = wx.BufferedPaintDC(self, self.buffer)
def DrawLines(self, dc):
for colour, thickness, line in self.lines:
pen = wx.Pen(colour, thickness, wx.SOLID)
dc.SetPen(pen)
for coords in line:
dc.DrawLine(*coords)
def SetColor(self, color):
self.color = color
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)
def SetThickness(self, num):
self.thickness = num
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)
class PaintFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Panit Frame", size = (800, 600))
self.paint = PaintWindow(self, -1)
#状态栏
self.paint.Bind(wx.EVT_MOTION, self.OnPaintMotion)
self.InitStatusBar()
#创建菜单
self.CreateMenuBar()
def InitStatusBar(self):
self.statusbar = self.CreateStatusBar()
#将状态栏分割为3个区域,比例为1:2:3
self.statusbar.SetFieldsCount(3)
self.statusbar.SetStatusWidths([-1, -2, -3])
def OnPaintMotion(self, event):
#设置状态栏1内容
self.statusbar.SetStatusText(u"鼠标位置:" + str(event.GetPositionTuple()), 0)
#设置状态栏2内容
self.statusbar.SetStatusText(u"当前线条长度:%s" % len(self.paint.curLine), 1)
#设置状态栏3内容
self.statusbar.SetStatusText(u"线条数目:%s" % len(self.paint.lines), 2)
event.Skip()
def MenuData(self):
'''
菜单数据
'''
#格式:菜单数据的格式现在是(标签, (项目)),其中:项目组成为:标签, 描术文字, 处理器, 可选的kind
#标签长度为2,项目的长度是3或4
return [("&File", ( #一级菜单项
("&New", "New paint file", self.OnNew), #二级菜单项
("&Open", "Open paint file", self.OnOpen),
("&Save", "Save paint file", self.OnSave),
("", "", ""), #分隔线
("&Color", (
("&Black", "", self.OnColor, wx.ITEM_RADIO), #三级菜单项,单选
("&Red", "", self.OnColor, wx.ITEM_RADIO),
("&Green", "", self.OnColor, wx.ITEM_RADIO),
("&Blue", "", self.OnColor, wx.ITEM_RADIO))),
("", "", ""),
("&Quit", "Quit", self.OnCloseWindow)))
]
def CreateMenuBar(self):
'''
创建菜单
'''
menuBar = wx.MenuBar()
for eachMenuData in self.MenuData():
menuLabel = eachMenuData[0]
menuItems = eachMenuData[1]
menuBar.Append(self.CreateMenu(menuItems), menuLabel)
self.SetMenuBar(menuBar)
def CreateMenu(self, menuData):
'''
创建一级菜单
'''
menu = wx.Menu()
for eachItem in menuData:
if len(eachItem) == 2:
label = eachItem[0]
subMenu = self.CreateMenu(eachItem[1])
menu.AppendMenu(wx.NewId(), label, subMenu) #递归创建菜单项
else:
self.CreateMenuItem(menu, *eachItem)
return menu
def CreateMenuItem(self, menu, label, status, handler, kind = wx.ITEM_NORMAL):
'''
创建菜单项内容
'''
if not label:
menu.AppendSeparator()
return
menuItem = menu.Append(-1, label, status, kind)
self.Bind(wx.EVT_MENU, handler,menuItem)
def OnNew(self, event):
pass
def OnOpen(self, event):
pass
def OnSave(self, event):
pass
def OnColor(self, event):
'''
更改画笔内容
'''
menubar = self.GetMenuBar()
itemid = event.GetId()
item = menubar.FindItemById(itemid)
color = item.GetLabel() #获取菜单项内容
self.paint.SetColor(color)
def OnCloseWindow(self, event):
self.Destroy()
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = PaintFrame(None)
frame.Show(True)
app.MainLoop()