944,017 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Unsolved
  • Views: 87740
  • Python RSS
You are currently viewing page 13 of this multi-page discussion thread; Jump to the first page
Sep 16th, 2009
1

Re: Starting wxPython (GUI code)

Just an experiment to explore the use of wxPython buttons to start and stop a process ...
python Syntax (Toggle Plain Text)
  1. # explore WxPython buttons to start and stop a process
  2. # set flag to 'stop' to allow exit
  3.  
  4. import wx
  5.  
  6. class MyFrame(wx.Frame):
  7. def __init__(self, parent, mytitle):
  8. wx.Frame.__init__(self, parent, -1, mytitle, size=(300, 200))
  9. self.SetBackgroundColour("yellow")
  10. self.start_btn = wx.Button(self, -1, label='Start')
  11. self.start_btn.Bind(wx.EVT_BUTTON, self.start_btnClick)
  12. self.stop_btn = wx.Button(self, -1, label='Stop')
  13. self.stop_btn.Bind(wx.EVT_BUTTON, self.stop_btnClick)
  14. self.label = wx.StaticText(self, -1, "-------")
  15.  
  16. # layout the widgets in a vertical order
  17. sizer_v = wx.BoxSizer(wx.VERTICAL)
  18. # Add(widget, proportion, flag, border)
  19. sizer_v.Add(self.start_btn, 0, flag=wx.ALL, border=10)
  20. sizer_v.Add(self.stop_btn, 0, flag=wx.ALL, border=10)
  21. sizer_v.Add(self.label, 0, flag=wx.ALL, border=10)
  22. self.SetSizer(sizer_v)
  23.  
  24. self.char = '>'
  25.  
  26. def start_btnClick(self, event):
  27. self.flag = 'start'
  28. self.processing()
  29.  
  30. def stop_btnClick(self, event):
  31. self.flag = 'stop'
  32. self.processing()
  33.  
  34. def processing(self):
  35. self.SetTitle(self.flag)
  36. while True:
  37. if self.flag == 'stop':
  38. break
  39. if self.flag == 'start':
  40. self.label.SetLabel(self.char)
  41. # needed to keep other processes going
  42. wx.GetApp().Yield()
  43. wx.Sleep(1)
  44. self.char += '>'
  45.  
  46.  
  47. app = wx.App(0)
  48. MyFrame(None, 'start and stop').Show()
  49. app.MainLoop()
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Sep 17th, 2009
0

excellent!

Thanks for this post--i suspect it will be way popular. Neither the wxPython book (Robin Dunn's "wxPython in Action", Manning publ.) nor the demo code in the wx distro bother with the lower-level mechanics of getting data into the PyGridTableBase instance, which is too bad because a fair amount of the Grid class is unlike the other wxWidget classes, so it's difficult to apply the wxWidget/wxPython conventions to grid widgets.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
alexLand is offline Offline
2 posts
since Jun 2008
Sep 17th, 2009
1

Re: Starting wxPython (GUI code)

Just a quick example on how to use the wx.grid.PyGridTableBase with wxPython's wx.grid.Grid. Provides a simple way to create, load and use a spreadsheet like grid:
python Syntax (Toggle Plain Text)
  1. # exploring wxPython's wx.grid.Grid()
  2. # load grid via a '(row, col): value' dictionary and a table class
  3. # that inherits and applies wx.grid.PyGridTableBase
  4. # snee
  5.  
  6. import wx
  7. import wx.grid
  8.  
  9. class MyFrame(wx.Frame):
  10. def __init__(self, header_list, data_dict):
  11. wx.Frame.__init__(self, None, wx.ID_ANY,
  12. title="ACME Inc. Staff Stats", size=(510,200))
  13.  
  14. self.grid = wx.grid.Grid(self)
  15. self.grid.SetRowLabelSize(30) # sets leading row width
  16. self.grid.SetDefaultRowSize(20) # sets all row height
  17. self.grid.SetColLabelSize(30) # sets leading col height
  18. self.grid.SetDefaultColSize(80) # sets all col width
  19.  
  20. # select the cell with a mouse left click
  21. self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.cell_click)
  22.  
  23. # the table takes care of all the grid stuff
  24. table = MyTable(header_list, data_dict)
  25. self.grid.SetTable(table, True)
  26.  
  27. # optional, calculate rows of data needed for fun stats
  28. self.rows = max(data_dict.keys())[0] + 1
  29.  
  30. def cell_click(self, event):
  31. """cell has been left clicked"""
  32. row = event.GetRow()
  33. col = event.GetCol()
  34. # move the grid's cursor to frame the cell
  35. self.grid.SetGridCursor(row, col)
  36. # you can do some fun stats with the numbers
  37. num = []
  38. if col > 0:
  39. #num = []
  40. for nrow in range(self.rows):
  41. num.append(float(self.grid.GetCellValue(nrow, col)))
  42. val = self.grid.GetCellValue(row, col)
  43. if num:
  44. sf = "r%dc%d %s max=%.1f min=%.1f avg=%.1f" % \
  45. (row, col, val, max(num), min(num), sum(num)/nrow)
  46. else:
  47. sf = "r%dc%d %s" % (row, col, val)
  48. self.SetTitle(sf)
  49.  
  50.  
  51. class MyTable(wx.grid.PyGridTableBase):
  52. def __init__(self, header_list, data_dict):
  53. wx.grid.PyGridTableBase.__init__(self)
  54. self.data = data_dict
  55. # calculate rows and cols needed to fit the data
  56. self.rows = max(data_dict.keys())[0] + 1
  57. self.cols = max(data_dict.keys())[1] + 1
  58. #print self.rows, self.cols # test
  59.  
  60. # label lists have to match row and column numbers
  61. # default for self.rowLabels = ["1", "2", "3", "4", "5", ...]
  62. # default for self.colLabels = ["A", "B", "C", "D", "E", ...]
  63. # however, we have custom column labels
  64. self.colLabels = header_list
  65.  
  66. # these are the five required methods ...
  67. def GetNumberRows(self):
  68. """actually sets number of rows"""
  69. return self.rows
  70.  
  71. def GetNumberCols(self):
  72. """actually sets number of cols"""
  73. return self.cols
  74.  
  75. def IsEmptyCell(self, row, col):
  76. return self.data.get((row, col)) is not None
  77.  
  78. def GetValue(self, row, col):
  79. """actually sets value of each (row, col)"""
  80. value = self.data.get((row, col))
  81. if value is not None:
  82. return value
  83. else:
  84. return ''
  85.  
  86. def SetValue(self, row, col, value):
  87. self.data[(row,col)] = value
  88.  
  89. # optional methods ...
  90. # allows the table to provide the attributes for each cell
  91. def GetAttr(self, row, col, kind):
  92. attr = wx.grid.GridCellAttr()
  93. attr.SetTextColour("black")
  94. attr.SetBackgroundColour("yellow")
  95. attr.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL))
  96. return attr
  97.  
  98. def GetColLabelValue(self, col):
  99. """you need to supply colLabels a list of labels"""
  100. return self.colLabels[col]
  101.  
  102. '''not needed, used default row labels here
  103. def GetRowLabelValue(self, row):
  104. """you need to supply rowLabels a list of labels"""
  105. return self.rowLabels[row]
  106. '''
  107.  
  108. header_list = ['Name', 'Age', 'Weight', 'Pay', 'Golf', 'Bowl']
  109. # raw data string could be from a csv file ...
  110. # columns are Name, Age, Weight, Pay, Golf avg, Bowling avg
  111. raw_data = """\
  112. Albert, 45, 230, 96000, 67, 210
  113. Curt, 22, 156, 34000, 56, 180
  114. Doris, 19, 112, 27000, 79, 133
  115. Larry, 34, 188, 57500, 49, 189
  116. Lupe, 24, 134, 42000, 83, 224
  117. Mark, 23, 202, 32000, 47, 201
  118. Rita, 22, 96, 23500, 87, 102
  119. Willy, 28, 286, 18000, 58, 134
  120. Zoe, 19, 120, 39000, 63, 156"""
  121.  
  122. # create a list of lists
  123. data_list = []
  124. for line in raw_data.split('\n'):
  125. line_list = line.split(',')
  126. data_list.append(line_list)
  127.  
  128. #print(data_list) # test
  129.  
  130. # create a dictionary of (row, col):value pairs
  131. data_dict = {}
  132. for row, item in enumerate(data_list):
  133. #print row, item
  134. for col, value in enumerate(item):
  135. data_dict[(row, col)] = value
  136.  
  137. #print(data_dict) # test
  138.  
  139. app = wx.App(0)
  140. MyFrame(header_list, data_dict).Show()
  141. app.MainLoop()
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006
Sep 20th, 2009
1

Re: Starting wxPython (GUI code)

A code example to show that wxPython does have a very flexible plotting widget. Here we graph the last 300 trading days (about 1 year) of a given company's closing stock values ...
python Syntax (Toggle Plain Text)
  1. # using wxPython's wx.lib.plot.PlotCanvas()
  2. # to show a line graph of some stock values
  3. # tested with Python25 and wxPython28
  4. # vegaseat
  5.  
  6. import wx
  7. import wx.lib.plot
  8. import urllib2
  9.  
  10. class MyFrame(wx.Frame):
  11. def __init__(self, data_list, start_date, end_date, ticker,
  12. max_val, min_val):
  13. wx.Frame.__init__(self, parent=None, id=-1,
  14. title="line graph of stock values",
  15. size=(600, 300))
  16.  
  17. # set up the plotting canvas
  18. plot_canvas = wx.lib.plot.PlotCanvas(self)
  19. # get client usable size of frame
  20. frame_size = self.GetClientSize()
  21. # needed for SaveFile() later
  22. plot_canvas.SetInitialSize(size=frame_size)
  23. # optional allow scrolling
  24. plot_canvas.SetShowScrollbars(True)
  25. # optional drag/draw rubberband area to zoom
  26. # doubleclick to return to original
  27. # right click to shrink
  28. plot_canvas.SetEnableZoom(True)
  29. # optional
  30. # set the tick and axis label font size (default is 10 point)
  31. plot_canvas.SetFontSizeAxis(point=8)
  32. # set title font size (default is 15 point)
  33. plot_canvas.SetFontSizeTitle(point=10)
  34.  
  35. # connect (x, y) points in data list with a line
  36. val_line = wx.lib.plot.PolyLine(data_list, colour='blue',
  37. width=1)
  38. # assign lines, title and axis labels
  39. title = "Latest 300 trading days of %s" % ticker
  40. x_axis = "Starting %s up to %s" % (start_date, end_date)
  41. y_axis = "value at close ($)"
  42. gc = wx.lib.plot.PlotGraphics([val_line],
  43. title, x_axis, y_axis)
  44. # draw the plot and set x and y axis sizes
  45. plot_canvas.Draw(gc, xAxis=(1, 300), yAxis=(min_val, max_val))
  46.  
  47. # optional save graph to an image file
  48. plot_canvas.SaveFile(fileName='stock1.jpg')
  49.  
  50.  
  51. ticker = "MSFT"
  52.  
  53. sf = 'http://ichart.finance.yahoo.com/table.csv?s=%s' % ticker
  54. url = urllib2.urlopen(sf)
  55. # read 17000 bytes or about the last 300+ days
  56. data = url.readlines(17000)
  57. data_lines = [line.rstrip().split(',') for line in data]
  58.  
  59. end_date = data_lines[1][0]
  60. start_date = data_lines[301][0]
  61. # look at the latest 300 trading days
  62. # and build a list of (day, close_value)
  63. data_list = []
  64. temp_list = []
  65. for day, line in enumerate(reversed(data_lines[1:301])):
  66. #print(line) # test
  67. close_value = float(line[4])
  68. data_list.append((day+1, close_value))
  69. temp_list.append(close_value)
  70. max_val = max(temp_list) + 3
  71. min_val = min(temp_list) - 3
  72.  
  73. print(len(data_lines), start_date, end_date, max_val, min_val) # test
  74.  
  75. app = wx.App(0)
  76. caption = "Line graph of stock values"
  77. frame = MyFrame(data_list, start_date, end_date, ticker, max_val,
  78. min_val)
  79. frame.Center()
  80. frame.Show()
  81. app.MainLoop()
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Oct 23rd, 2009
1

Rainbow text

You can create rather colorful text using html code and wxPython's wx.html.HtmlWindow widget. Here we use a small function to help us generate html code ...
python Syntax (Toggle Plain Text)
  1. # use wxPython's wx.html.HtmlWindow to create colorful text
  2. # tested with Python25 and wxPython28 by vegaseat
  3.  
  4. import wx
  5. import wx.html
  6.  
  7. def do_html(text, color='black', size=3):
  8. """create a line of html code for text with color and size"""
  9. sf = "<FONT color=%s size=%d>%s</FONT>"
  10. return sf % (color, size, text)
  11.  
  12.  
  13. # build up simple HTML code ...
  14. # text between <B> and </B> is bold
  15. # <BR> inserts a line break (new line)
  16. html = ""
  17. html += do_html("Create colorful text ", "red")
  18. html += do_html("with html code to be", "blue")
  19. html += '<BR>'
  20. html += do_html("displayed in wxPython's ", "green")
  21. html += do_html("wx.html.HtmlWindow", "brown")
  22. html += '<BR><BR>'
  23. orange = "#FFBA00" # gives a better orange color
  24. color_list = ['red', orange, 'yellow', 'green', 'blue']
  25. ix = 0
  26. for c in 'WE LOVE RAINBOWS':
  27. # make character c bold
  28. c = "<B>" + c + "</B>"
  29. if ix >= len(color_list):
  30. ix = 0
  31. html += do_html(c, color_list[ix], 7)
  32. ix += 1
  33.  
  34.  
  35. # set up the GUI window/frame ...
  36. app = wx.App(0)
  37. mytitle = "wx.html.HtmlWindow for colorful text"
  38. width = 420
  39. height = 160
  40. # make parent None
  41. frame = wx.Frame(None, id=-1, size=(width, height), title=mytitle)
  42. # create an html label/window
  43. htmlwin = wx.html.HtmlWindow(parent=frame, id=-1)
  44. # display the html code
  45. htmlwin.SetPage(html)
  46. frame.Show(True)
  47. frame.Center()
  48. app.MainLoop()
Attached Thumbnails
Click image for larger version

Name:	wx_rainbow.jpg
Views:	503
Size:	17.3 KB
ID:	12277  
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Oct 27th, 2009
1
Re: Starting wxPython (GUI code)
Its time to explore wxPython's wx.Timer() and wx.StopWatch() widgets. The stopwatch works in the background to track the length of a process ...
python Syntax (Toggle Plain Text)
  1. # explore wxPython
  2. # wx.Timer() one_shot and wx.StopWatch() example
  3. # a one_shot delays for a set time
  4. # tested with Python25 and wxPython28 by vegaseat
  5.  
  6. import wx
  7.  
  8. class MyFrame(wx.Frame):
  9. def __init__(self, parent, mytitle, mysize):
  10. wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
  11. self.SetBackgroundColour('red')
  12. self.watch = wx.StopWatch()
  13.  
  14. self.timer = wx.Timer(self)
  15. # interval = 2000ms (2 seconds)
  16. # default is oneShot=False, timer keeps restarting
  17. self.timer.Start(2000, oneShot=True)
  18. self.watch.Start()
  19. self.SetTitle("stopwatch started")
  20. # bind EVT_TIMER event to self.onTimer() action
  21. self.Bind(wx.EVT_TIMER, self.onTimer)
  22.  
  23. def onTimer(self, event):
  24. # establish new color
  25. self.SetBackgroundColour('green')
  26. # clear old color, set to new color
  27. self.ClearBackground()
  28. # pause/stop the stopwatch and get its time
  29. self.watch.Pause()
  30. time = self.watch.Time()
  31. s = "stopwatch stopped at %s milliseconds" % time
  32. self.SetTitle(s)
  33.  
  34.  
  35. app = wx.App(0)
  36. # create a MyFrame instance and show the frame
  37. MyFrame(None, '---', (500, 100)).Show()
  38. app.MainLoop()
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 7th, 2009
2
Re: Starting wxPython (GUI code)
Just testing wxPython's wx.TextCtrl widget used as an edit field for input and output of text based data:
python Syntax (Toggle Plain Text)
  1. # testing wxPython's
  2. # wx.TextCtrl(parent, id, value, pos, size, style)
  3. # a widget used for text data input or output
  4. # note:
  5. # style=wx.TE_PROCESS_ENTER is needed for Linux to
  6. # respond to the enter key event!!!
  7. # snee
  8.  
  9. import wx
  10.  
  11. class MyFrame(wx.Frame):
  12. def __init__(self, parent, mytitle, mysize):
  13. wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
  14. self.SetBackgroundColour("yellow")
  15.  
  16. s = "Enter name below:"
  17. edit_label = wx.StaticText(self, wx.ID_ANY, s)
  18. # create a single line edit input area
  19. self.edit = wx.TextCtrl(self, wx.ID_ANY, value="",
  20. style=wx.TE_PROCESS_ENTER)
  21. # put the cursor in edit
  22. self.edit.SetFocus()
  23. # respond to enter key when focus is on edit
  24. self.edit.Bind(wx.EVT_TEXT_ENTER, self.onEnter)
  25.  
  26. # create a scrolled multiline text output area
  27. self.text_out = wx.TextCtrl(self, wx.ID_ANY, value="",
  28. style=wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY)
  29.  
  30. # use a box sizer for vertical widget layout
  31. sizer = wx.BoxSizer(wx.VERTICAL)
  32. sizer.Add(edit_label, 0, wx.LEFT|wx.TOP|wx.EXPAND, border=10)
  33. sizer.Add(self.edit, 0, wx.ALL|wx.EXPAND, border=10)
  34. sizer.Add(self.text_out, 2, wx.ALL|wx.EXPAND, border=10)
  35. self.SetSizer(sizer)
  36.  
  37. def onEnter(self, event):
  38. """the Enter key has been pressed, do something"""
  39. # GetValue() gives a string
  40. name = self.edit.GetValue()
  41. s = "You entered the name: " + name + '\n'
  42. # text output, either method works
  43. #self.text_out.AppendText(s)
  44. self.text_out.WriteText(s)
  45. # clear edit input space
  46. self.edit.Clear()
  47.  
  48.  
  49. app = wx.App(0)
  50. # create a MyFrame instance and show the frame
  51. MyFrame(None, 'testing wx.TextCtrl()', (300, 480)).Show()
  52. app.MainLoop()
Notice the special requirement for Linux users.
Last edited by sneekula; Nov 7th, 2009 at 3:31 pm.
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006
Nov 23rd, 2009
0
Re: Starting wxPython (GUI code)
This simple wxPython slide show uses the wx.PaintDC surface as a canvas that can be cleared between pictures ...
python Syntax (Toggle Plain Text)
  1. # create a simple image slide show using the
  2. # wx.PaintDC surface as a canvas and
  3. # DrawBitmap(bitmap, x, y, bool transparent)
  4. # vegaseat
  5.  
  6. import wx
  7. import os
  8.  
  9. class ShowPic(wx.Frame):
  10.  
  11. def __init__(self, parent):
  12. wx.Frame.__init__(self, parent, wx.ID_ANY, 'MyFrame',
  13. size=(773,632))
  14. self.panel = wx.Panel(self)
  15.  
  16. # seconds per slide
  17. self.delay = 2
  18. # number of loops per slide show
  19. self.loops = 2
  20.  
  21. # list of image files you have in the working directory
  22. self.images = ["Pic1.png", "Pic2.png", "Pic3.png"]
  23.  
  24. # create a list of bitmap image objects
  25. self.image_list = []
  26. for image_file in self.images:
  27. if os.path.exists(image_file):
  28. print(image_file) # test
  29. self.image_list.append(wx.Bitmap(image_file))
  30. else:
  31. self.SetTitle("No pictures found!")
  32.  
  33. # bind the panel to the paint event
  34. wx.EVT_PAINT(self.panel, self.onPaint)
  35.  
  36. def onPaint(self, event=None):
  37. # this is the wxPython drawing surface/canvas
  38. dc = wx.PaintDC(self.panel)
  39. while self.loops:
  40. self.loops -= 1
  41. for ix, bmp in enumerate(self.image_list):
  42. # clear the canvas
  43. dc.Clear()
  44. # optionally show image name
  45. self.SetTitle(self.images[ix])
  46. # draw the image
  47. dc.DrawBitmap(bmp, 10, 10, True)
  48. # wait self.delay seconds to show next slide
  49. wx.Sleep(self.delay)
  50.  
  51.  
  52. if __name__=='__main__':
  53. app = wx.App(0)
  54. frame = ShowPic(parent=None)
  55. frame.Show()
  56. app.MainLoop()
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Dec 7th, 2009
1
Re: Starting wxPython (GUI code)
This code shows you how to create a drawing on a wxPython canvas and save the drawing to a standard image file ...
python Syntax (Toggle Plain Text)
  1. # use a drawing bitmap and wx.MemoryDC to create a canvas you can
  2. # draw on and optionally save the drawing to an image file
  3. # vegaseat
  4.  
  5. import wx
  6.  
  7. class MyFrame(wx.Frame):
  8. def __init__(self, parent, title):
  9. wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(400, 150))
  10. # create a bitmp for display and optional saving
  11. self.show_bmp = wx.StaticBitmap(self)
  12. # get the width and height for the blank bitmap
  13. w, h = self.GetClientSize()
  14. # create a blank bitmap as a drawing background
  15. draw_bmp = wx.EmptyBitmap(w, h)
  16. # put the canvas on top of draw_bmp
  17. canvas = wx.MemoryDC(draw_bmp)
  18. # fill the canvas white
  19. canvas.SetBrush(wx.Brush('white'))
  20. canvas.Clear()
  21.  
  22. # now draw something on the canvas ...
  23. # set line colour and thickness (pixels)
  24. canvas.SetPen(wx.Pen("blue", 15))
  25. # DrawLine(x1, y1, x2, y2) from point (x1,y1) to (x2,y2)
  26. canvas.DrawLine(50, 60, 340, 60)
  27.  
  28. # this also shows your drawing
  29. self.show_bmp.SetBitmap(draw_bmp)
  30.  
  31. # optioally save the created image
  32. # get the image object
  33. myimage = self.show_bmp.GetBitmap()
  34. myimage.SaveFile("myimage.jpg", wx.BITMAP_TYPE_JPEG)
  35.  
  36.  
  37. app = wx.App(0)
  38. MyFrame(None, 'draw a line using wx.MemoryDC').Show(True)
  39. app.MainLoop()
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Dec 16th, 2009
0
Re: Starting wxPython (GUI code)
I modified the code in the previous post to join two images into one:
python Syntax (Toggle Plain Text)
  1. # use a drawing bitmap and wx.MemoryDC to create a canvas you can
  2. # draw on and optionally save the drawing to an image file
  3. # here we draw two images side by side and save the combined image
  4. # vegaseat code modified by sneek
  5.  
  6. import wx
  7.  
  8. class MyFrame(wx.Frame):
  9. def __init__(self, parent, title, mysize):
  10. wx.Frame.__init__(self, parent, -1, title, size=mysize)
  11. # create a bitmp for display and optional saving
  12. self.show_bmp = wx.StaticBitmap(self)
  13. # get the width and height for the blank bitmap
  14. w, h = self.GetClientSize()
  15. # create a blank bitmap as a drawing background
  16. # should be large enough to fit the 2 images side by side
  17. draw_bmp = wx.EmptyBitmap(w, h)
  18.  
  19. # put a canvas on top of draw_bmp
  20. canvas = wx.MemoryDC(draw_bmp)
  21.  
  22. # fill the canvas white
  23. canvas.SetBrush(wx.Brush('white'))
  24. canvas.Clear()
  25.  
  26. # pick 2 image files you have in the working folder
  27. # (can be a .jpg, .png, .gif, .bmp image files)
  28. # note that filenames are case sensitive in Linux
  29. image1 = wx.Bitmap("Duck_right.jpg")
  30. image2 = wx.Bitmap("Duck_left.jpg")
  31.  
  32. # draw the 2 images side by side
  33. canvas.DrawBitmap(image1, 0, 0)
  34. canvas.DrawBitmap(image2, w/2, 0)
  35.  
  36. # this also shows your drawing
  37. self.show_bmp.SetBitmap(draw_bmp)
  38.  
  39. # get the image object
  40. myimage = self.show_bmp.GetBitmap()
  41. # save it to a file
  42. myimage.SaveFile("joined_pic1.jpg", wx.BITMAP_TYPE_JPEG)
  43.  
  44.  
  45. app = wx.App(0)
  46. # make width w large enough to have the 2 images next to each other
  47. w = 610
  48. # make height h large enough to fit the max height of the 2 images
  49. h = 210
  50. mysize = (w, h)
  51. MyFrame(None, 'join two images and save', mysize).Show(True)
  52. app.MainLoop()
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: wxpython image covering
Next Thread in Python Forum Timeline: Difficulty importing a file with a class definition





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC