Jun 12, 2010

wxpython 总结例子和 wxpython+opencv 框架

wxpython+opencv 框架
以后可以在此基础上添加功能

#!/usr/bin/python

# submenu.py

import wx
import os
import cv

# For each item that triggers an event, allocate one ID
# Maybe you want to differentiate menu, toolbar, and others event sources

ID_OPEN = 1
ID_CLOSE = 2 
ID_QUIT = 3

ID_PROC_GRAY = 11

ID_TOOL_OPEN = 101
ID_TOOL_CLOSE = 102



#iconpath = r'/home/bee33/win/Basic_set_Png'
iconpath = r'G:\win\Basic_set_Png'

# Context menu
class ImagePanel(wx.Panel):
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        
        self.bmp = None
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        
    def OnPaint(self, event):
        dc = wx.PaintDC(self)
#        print 'In Panel'
        if self.bmp:
            dc.DrawBitmap(self.bmp, 0, 0)
            
    def SetBmp(self, bmp):
        self.bmp = bmp


class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(400, 600))
        
        # Set icon
        icon = wx.EmptyIcon()
        icon.CopyFromBitmap(wx.Bitmap(os.path.join(iconpath,'buy_16.png'), wx.BITMAP_TYPE_ANY))
        self.SetIcon(icon)
        
        # Menubar
        menubar = wx.MenuBar()
        
        # Menu 1
        file = wx.Menu()
        file.Append(ID_OPEN, '&Open', 'Open an image')
        file.Append(ID_CLOSE, '&Close', 'Close the image')
        file.Append(ID_QUIT, '&Quit')
        

        # Menu 2
        proc_menu = wx.Menu()
        
        proc_menu.Append(ID_PROC_GRAY, 'RGB->&Gray', 'RGB->Gray')


        # Finally, the end for menu parts
        menubar.Append(file, '&File')
        menubar.Append(proc_menu, '&View')
        self.SetMenuBar(menubar)

        # Toolbar        
        self.toolbar = self.CreateToolBar()
        self.toolbar.AddLabelTool(ID_TOOL_OPEN, '', wx.Bitmap(os.path.join(iconpath,'open16.png')),longHelp='Open a new image')
        self.toolbar.AddLabelTool(ID_TOOL_CLOSE, '', wx.Bitmap(os.path.join(iconpath,'close16.png')),longHelp='Close the image')
        self.toolbar.Realize()
        
        # Status bar
        self.statusbar = self.CreateStatusBar()

        ########### Client Area #############        
        panel = wx.Panel(self, -1)
        

        # it is void, only shows how to deal with background color
        #panel.SetBackgroundColour(panel.GetBackgroundColour())
        
        #########  Which sizer to use ############
        # wx.BoxSizer: a row or a column. We can put another sizer into an existing sizer.
        
        # wx.StaticBoxSizer: Identical to a wx.BoxSizer, with the one addition of a border (and optional
        # caption) around the box.
         
        # wx.GridSizer lays out widgets in two dimensional table. 
        # Each cell within the table has the same size.
         
        # wx.FlexGridSizer: All cells in a row have the same height. 
        # All cells in a column have the same width. 
        # But all rows and columns are not necessarily the same height or width. 
        
        # box.Add(wx.Window window, integer proportion=0, integer flag = 0, integer border = 0)
        # proportion: 0 - Do not change size
        # it is relative, item with 2 changes twice the degree of item with 1  
        # 
        # Flag: 
        #    wx.EXPAND: strech to the possible size
        #    wx.LEFT
        #    wx.RIGHT
        #    wx.BOTTOM
        #    wx.TOP
        #    wx.ALL: all the above are border margin flags
        #    wx.ALIGN_LEFT
        #    wx.ALIGN_RIGHT
        #    wx.ALIGN_TOP
        #    wx.ALIGN_BOTTOM
        #    wx.ALIGN_CENTER_VERTICAL
        #    wx.ALIGN_CENTER_HORIZONTAL
        #    wx.ALIGN_CENTER: the above are item alignment flags

        # top sizer
        vbox_top = wx.BoxSizer(wx.HORIZONTAL)


        # Info Panel
        pnlinfo = wx.Panel(panel, -1)
        sbox1 = wx.StaticBoxSizer(wx.StaticBox(pnlinfo, -1, 'Info'), orient=wx.VERTICAL)
        self.infost = wx.StaticText(pnlinfo, -1, '')
        sbox1.Add(self.infost)
        pnlinfo.SetSizer(sbox1)
        
        
        
        # part 5, image panel
        self.pnlimage = ImagePanel(panel, -1)

        self.img = None
        
        
        # a sizer can add a panel or another sizer
        vbox_top.Add(self.pnlimage, 2, wx.EXPAND|wx.ALL, 5)
        vbox_top.Add(pnlinfo,  1, wx.EXPAND|wx.ALL, 5)
        
        # set top sizer
        panel.SetSizer(vbox_top)


        ########## Event binding ##############
        
        # Menu events binding
        self.Bind(wx.EVT_MENU, self.OnOpen, id=ID_OPEN)
        self.Bind(wx.EVT_MENU, self.OnClose, id=ID_CLOSE)
        self.Bind(wx.EVT_MENU, self.OnQuit, id=ID_QUIT)
        
        
        # Tool events binding
        self.Bind(wx.EVT_TOOL, self.OnOpen, id=ID_TOOL_OPEN)
        self.Bind(wx.EVT_TOOL, self.OnClose, id=ID_TOOL_CLOSE)
        
#        self.Bind(wx.EVT_PAINT, self.OnPaint)

        
        self.Bind(wx.EVT_MENU, self.OnGray, id=ID_PROC_GRAY)



        # Show the frame
        self.Centre()
        self.Show(True)

    ########## Event Handlers #############
    def OnOpen(self, event):
        wildcard = "Other Image files (*.*)|*.*|" \
        "PNG Image (*.png)|*.png|" \
        "JPG Image (*.jpg)|*.jpg"
        
        dialog = wx.FileDialog(None, "Choose a file", os.getcwd(),
                               "", wildcard, wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            self.img = cv.LoadImage(dialog.GetPath())
            self.infost.SetLabel('LaLaLa')
            self.SetColorImg(self.img)
            self.Refresh()
        
    def OnClose(self, event):
        self.img = None
        self.pnlimage.SetBmp(None)
        self.infost.SetLabel('')
        self.Refresh()
        
    def OnQuit(self, event):
        self.Close()
        
       
    def OnGray(self, event):
        if self.img:
            img2 = cv.CreateImage(cv.GetSize(self.img), cv.IPL_DEPTH_8U, 1)
            cv.CvtColor(self.img, img2, cv.CV_BGR2GRAY)
            self.SetGrayImg(img2)
            self.Refresh()
            
        
    def SetColorImg(self, img):
        if img:
            img2 = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 3)
            cv.CvtColor(img, img2, cv.CV_BGR2RGB)
            bmp = wx.BitmapFromBuffer(img2.width, img2.height, img2.tostring())
            self.pnlimage.SetBmp(bmp)
            
    def SetGrayImg(self, img):
        if img:
            # unless other method of creating wx.Bitmap from gray cv image is found
            # Here we create a color image by copying planes
            img2 = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 3)
            cv.Merge(img,img,img,None,img2)
            self.SetColorImg(img2)
                   
  


app = wx.App(False)
MyFrame(None, -1, 'wxPython Template')
app.MainLoop()

wxpython 总结例子

#!/usr/bin/python

# submenu.py

import wx
import os

# For each item that triggers an event, allocate one ID
# Maybe you want to differentiate menu, toolbar, and others event sources
ID_QUIT = 1
ID_NEW = 2

ID_TOOL_EXIT = 3

ID_STAT = 11
ID_TOOL = 13

ID_RADIO1 = 14
ID_RADIO2 = 15

ID_TOOL_ENABLE = 21
ID_TOOL_DISABLE = 22

#iconpath = r'/home/bee33/win/Basic_set_Png'
iconpath = r'G:\win\Basic_set_Png'

# Context menu
class MyPopupMenu(wx.Menu):
    def __init__(self, parent):
        wx.Menu.__init__(self)

        self.parent = parent

        minimize = wx.MenuItem(self, wx.NewId(), 'Minimize')
        self.AppendItem(minimize)
        self.Bind(wx.EVT_MENU, self.OnMinimize, id=minimize.GetId())

    def OnMinimize(self, event):
        self.parent.Iconize()


class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(400, 600))
        
        # Set icon
        icon = wx.EmptyIcon()
        icon.CopyFromBitmap(wx.Bitmap(os.path.join(iconpath,'buy_16.png'), wx.BITMAP_TYPE_ANY))
        self.SetIcon(icon)
        
        # Menubar
        menubar = wx.MenuBar()
        
        # Menu 1
        file = wx.Menu()
        file.Append(ID_NEW, '&New', 'New in Statusbar')
        file.Append(-1, '&Open')
        file.Append(-1, '&Save')
        file.AppendSeparator()
        
        # Submenu of Menu 1. Note it is also wx.Menu
        imp = wx.Menu()
        imp.Append(-1, 'Import newsfeed list...')
        imp.Append(-1, 'Import bookmarks...')
        imp.Append(-1, 'Import mail...')
        file.AppendMenu(-1, 'I&mport', imp)

        quit = wx.MenuItem(file, ID_QUIT, '&Quit\tCtrl+W')
        quit.SetBitmap(wx.Bitmap(os.path.join(iconpath,'left_16.png')))
        file.AppendItem(quit)

        # Menu 2
        view = wx.Menu()
        
        # 'Check' type Menu
        self.shst = view.Append(ID_STAT, 'Show statubar', 'Show Statusbar', kind=wx.ITEM_CHECK)
        self.shtl = view.Append(ID_TOOL, 'Show toolbar', 'Show Toolbar', kind=wx.ITEM_CHECK)
        view.Check(ID_STAT, True)
        view.Check(ID_TOOL, True)
        
        # 'Radio' type Menu
        self.radio1 = view.AppendRadioItem(ID_RADIO1, 'Show statubar', 'Show Statusbar')
        self.radio2 = view.AppendRadioItem(ID_RADIO2, 'Hide statubar', 'Hide Statusbar')


        # Finally, the end for menu parts
        menubar.Append(file, '&File')
        menubar.Append(view, '&View')
        self.SetMenuBar(menubar)

        # Toolbar        
        self.toolbar = self.CreateToolBar()
        self.toolbar.AddLabelTool(ID_TOOL_EXIT, '', wx.Bitmap(os.path.join(iconpath,'left_16.png')))
        self.toolbar.AddLabelTool(ID_TOOL_ENABLE, '', wx.Bitmap(os.path.join(iconpath,'tick_16.png')),longHelp='Enable Exit Tool')
        self.toolbar.AddLabelTool(ID_TOOL_DISABLE, '', wx.Bitmap(os.path.join(iconpath,'delete_16.png')), shortHelp='Disable Exit Tool')
        self.toolbar.Realize()
        
        # Status bar
        self.statusbar = self.CreateStatusBar()

        ########### Client Area #############        
        panel = wx.Panel(self, -1)
        

        # it is void, only shows how to deal with background color
        panel.SetBackgroundColour(panel.GetBackgroundColour())
        
        #########  Which sizer to use ############
        # wx.BoxSizer: a row or a column. We can put another sizer into an existing sizer.
        
        # wx.StaticBoxSizer: Identical to a wx.BoxSizer, with the one addition of a border (and optional
        # caption) around the box.
         
        # wx.GridSizer lays out widgets in two dimensional table. 
        # Each cell within the table has the same size.
         
        # wx.FlexGridSizer: All cells in a row have the same height. 
        # All cells in a column have the same width. 
        # But all rows and columns are not necessarily the same height or width. 
        
        # box.Add(wx.Window window, integer proportion=0, integer flag = 0, integer border = 0)
        # proportion: 0 - Do not change size
        # it is relative, item with 2 changes twice the degree of item with 1  
        # 
        # Flag: 
        #    wx.EXPAND: strech to the possible size
        #    wx.LEFT
        #    wx.RIGHT
        #    wx.BOTTOM
        #    wx.TOP
        #    wx.ALL: all the above are border margin flags
        #    wx.ALIGN_LEFT
        #    wx.ALIGN_RIGHT
        #    wx.ALIGN_TOP
        #    wx.ALIGN_BOTTOM
        #    wx.ALIGN_CENTER_VERTICAL
        #    wx.ALIGN_CENTER_HORIZONTAL
        #    wx.ALIGN_CENTER: the above are item alignment flags

        # top sizer
        vbox_top = wx.BoxSizer(wx.VERTICAL)

        # Part 1 - Absolute positioning
        pab = wx.Panel(panel, -1)
        wx.TextCtrl(pab, -1, pos=(-1, -1), size=(250, 40))
        
        # part2 - box sizer
        # note that hbox is on the top of this part
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        panel3 = wx.Panel(panel, -1)
        panel3.SetBackgroundColour('#808080')
        panel4 = wx.Panel(panel, -1)
        panel4.SetBackgroundColour('#404040')
        hbox.Add(panel3,1,wx.EXPAND|wx.ALL,5)
        hbox.Add(panel4,2,wx.EXPAND|wx.ALL,5)
        
        # part 3 - static box
        sbox = wx.StaticBoxSizer(wx.StaticBox(panel, -1, 'Direction'), orient=wx.VERTICAL) 
        # take panel as its parent, rather than treat panel as a static box
        sbox.Add(wx.RadioButton(panel, -1, 'Forward', style=wx.RB_GROUP))
        sbox.Add(wx.RadioButton(panel, -1, 'Backward'))
        
        # part 4 - grid
        panel1 = wx.Panel(panel, -1)
        grid1 = wx.GridSizer(2, 2)
        grid1.Add(wx.StaticText(panel1, -1, 'Find: ', (5, 5)), 0,  wx.ALIGN_CENTER_VERTICAL)
        grid1.Add(wx.ComboBox(panel1, -1, size=(120, -1)))
        grid1.Add(wx.StaticText(panel1, -1, 'Replace with: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL)
        grid1.Add(wx.ComboBox(panel1, -1, size=(120, -1)))
        panel1.SetSizer(grid1)
        
        # part 5, image panel
        self.panel5 = wx.Panel(panel, -1)
        self.sbp = wx.StaticBitmap(self.panel5, -1, wx.Bitmap('../glove.jpg'))
        
        
        # a sizer can add a panel or another sizer
        vbox_top.Add(pab,  0, wx.EXPAND|wx.ALL, 5)
        vbox_top.Add(hbox, 0, wx.EXPAND|wx.ALL, 5)
        vbox_top.Add(sbox, 0, wx.EXPAND|wx.ALL, 5)
        vbox_top.Add(panel1, 0, wx.EXPAND|wx.ALL, 5)
        vbox_top.Add(self.panel5, 1, wx.EXPAND|wx.ALL, 5)
        
        # set top sizer
        panel.SetSizer(vbox_top)

        # Show the frame
        self.Centre()
        self.Show(True)


        ########## Event binding ##############
        
        # Menu events binding
        self.Bind(wx.EVT_MENU, self.OnQuit, id=ID_QUIT)
        self.Bind(wx.EVT_MENU, self.OnNew, id=ID_NEW)
        self.Bind(wx.EVT_MENU, self.ToggleStatusBar, id=ID_STAT)
        self.Bind(wx.EVT_MENU, self.ToggleToolBar, id=ID_TOOL)
        
        # For radio menu events, their share the same handler
        self.Bind(wx.EVT_MENU, self.ToggleRadio, id=ID_RADIO1)
        self.Bind(wx.EVT_MENU, self.ToggleRadio, id=ID_RADIO2)
        
        # Context Menu
        self.sbp.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
        
        # Tool events binding
        self.Bind(wx.EVT_TOOL, self.OnToolExit, id=ID_TOOL_EXIT)
        self.Bind(wx.EVT_TOOL, self.OnToolEnable, id=ID_TOOL_ENABLE)
        self.Bind(wx.EVT_TOOL, self.OnToolDisable, id=ID_TOOL_DISABLE)


    ########## Event Handlers #############
    def OnQuit(self, event):
        self.Close()
        
    def OnNew(self, event):
        wx.MessageBox('New')
        
    def ToggleStatusBar(self, event):
        if self.shst.IsChecked():
            self.statusbar.Show()
        else:
            self.statusbar.Hide()

    def ToggleToolBar(self, event):
        if self.shtl.IsChecked():
            self.toolbar.Show()
        else:
            self.toolbar.Hide()
            
    def ToggleRadio(self, event):
        if self.radio1.IsChecked():
            self.toolbar.Show()
        if self.radio2.IsChecked():
            self.toolbar.Hide()

    def OnRightDown(self, event):
#        self.sbp.GetPosition()
        self.PopupMenu(MyPopupMenu(self), self.panel5.GetPosition()+event.GetPosition()+(0,5))
        
    def OnToolExit(self, event):
        self.Destroy()
        
    def OnToolEnable(self, event):
        self.toolbar.EnableTool(ID_TOOL_EXIT, True)        
        
    def OnToolDisable(self, event):
        self.toolbar.EnableTool(ID_TOOL_EXIT, False)



app = wx.App(False)
MyFrame(None, -1, 'wxPython Template')
app.MainLoop()

0 comments: