Starting wxPython (GUI code)

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Aug 2005
Posts: 1,546
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 174
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting wxPython (GUI code)

 
0
  #51
Aug 4th, 2008
You can use several classes in your wxPython program. This example shows you how to cross reference a widget (or variable) from one class to another:
  1. # experiments with wxPython, reference across class instances
  2. # from one panel class to another panel class
  3.  
  4. import wx
  5. import time
  6.  
  7. class MakePanel1(wx.Panel):
  8. def __init__(self, Parent, *args, **kwargs):
  9. wx.Panel.__init__(self, Parent, *args, **kwargs)
  10. self.SetBackgroundColour('yellow')
  11.  
  12. self.label = wx.StaticText(self, -1, " panel1 label ")
  13.  
  14. self.hbox = wx.BoxSizer(wx.HORIZONTAL)
  15. self.hbox.Add(self.label, 0, wx.ALL, 20)
  16. self.SetSizer(self.hbox)
  17.  
  18.  
  19. class MakePanel2(wx.Panel):
  20. def __init__(self, Parent, *args, **kwargs):
  21. wx.Panel.__init__(self, Parent, *args, **kwargs)
  22. self.SetBackgroundColour('green')
  23.  
  24. self.button = wx.Button(self, label=" panel2 button ")
  25. self.button.Bind(wx.EVT_BUTTON, self.buttonClick )
  26.  
  27. self.hbox = wx.BoxSizer(wx.HORIZONTAL)
  28. self.hbox.Add(self.button, 0, wx.ALL, 20)
  29. self.SetSizer(self.hbox)
  30.  
  31. def buttonClick(self, event=None):
  32. # reference panel1's label via frame.panel1
  33. s1 = "panel1 label ..... \n"
  34. s2 = "the time is " + time.strftime("%H:%M:%S", time.localtime())
  35. frame.panel1.label.SetLabel(s1 + s2)
  36.  
  37.  
  38. class MakeFrame(wx.Frame):
  39. def __init__(self, *args, **kwargs):
  40. wx.Frame.__init__(self, *args, **kwargs)
  41.  
  42. self.panel1 = MakePanel1(self)
  43. self.panel2 = MakePanel2(self)
  44.  
  45. vbox = wx.BoxSizer(wx.VERTICAL)
  46. vbox.Add(self.panel1,1,wx.EXPAND);
  47. vbox.Add(self.panel2,1,wx.EXPAND);
  48. self.SetSizer(vbox)
  49. # select a frame size so everything fits
  50. self.Fit()
  51.  
  52.  
  53. app = wx.App(0)
  54. # instance frame is needed for later reference
  55. frame = MakeFrame(None)
  56. frame.Show(True)
  57. app.MainLoop()
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,546
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 174
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting wxPython (GUI code)

 
0
  #52
Aug 4th, 2008
If you like to draw things, here is an example how to draw some basic shapes on wxPython's canvas:
  1. # draw a few well known shapes on a wx.PaintDC() canvas
  2.  
  3. import wx
  4.  
  5. class MyFrame(wx.Frame):
  6. def __init__(self, parent=None, title=None):
  7. wx.Frame.__init__(self, parent, wx.ID_ANY, title)
  8. self.panel = wx.Panel(self, size=(350, 450))
  9. # this sets up the painting canvas
  10. self.panel.Bind(wx.EVT_PAINT, self.on_paint)
  11. # set frame size to fit panel
  12. self.Fit()
  13.  
  14. def on_paint(self, event):
  15. # establish the painting canvas
  16. dc = wx.PaintDC(self.panel)
  17.  
  18. # draw some lines using the given pen specs
  19. # from points (x1, y1) to (x2, y2)
  20. x1 = 50
  21. y1 = 20
  22. x2 = 300
  23. y2 = 20
  24. # first pen colour is red (thickness = 5)
  25. dc.SetPen(wx.Pen('red', 5))
  26. dc.DrawLine(x1, y1, x2, y2)
  27. # second pen colour is white
  28. dc.SetPen(wx.Pen('white', 5))
  29. dc.DrawLine(x1, y1+5, x2, y2+5)
  30. # third pen colour is blue
  31. dc.SetPen(wx.Pen('blue', 5))
  32. dc.DrawLine(x1, y1+10, x2, y2+10)
  33.  
  34. # draw a red rounded-rectangle
  35. # upper left corner coordinates x, y and width, height
  36. # make the pen colour red (thickness = 1)
  37. # default brush (fill) is white
  38. dc.SetPen(wx.Pen('red', 1))
  39. x = 50
  40. y = 50
  41. w = 100
  42. h = 100
  43. rect = wx.Rect(x, y, w, h)
  44. # corners are quarter-circles using a radius of 8
  45. dc.DrawRoundedRectangleRect(rect, 8)
  46.  
  47. # draw a red circle with yellow fill
  48. # center coordinates x, y and radius r
  49. dc.SetBrush(wx.Brush('yellow'))
  50. x = 250
  51. y = 100
  52. r = 50
  53. dc.DrawCircle(x, y, r)
  54.  
  55. # draw an arc from point x1, y1 to point x2, y2 counter
  56. # clockwise along a circle with center xc, yc
  57. # use previous pen and brush settings
  58. xc = 100
  59. yc = 220
  60. x1 = xc
  61. y1 = 170
  62. x2 = xc
  63. y2 = 270
  64. dc.DrawArc(x1, y1, x2, y2, xc, yc)
  65.  
  66. # draw a polygon connecting the (x, y) points in a list
  67. # will also connect first and last points
  68. point_list = [(10, 10), (120, 20), (100, 80), (50, 100)]
  69. dc.DrawPolygon(point_list, xoffset=180, yoffset=170)
  70.  
  71. # draw 2 gradient filled rectangles
  72. # upper left corner coordinates x, y and width, height
  73. x = 50
  74. y = 300
  75. w = 100
  76. h = 100
  77. dc.DrawRectangle(x, y, w, h)
  78. dc.GradientFillLinear((x, y, w, h), 'red', 'blue')
  79. # just a little different fill
  80. dc.DrawRectangle(x+150, y, w, h)
  81. dc.GradientFillConcentric((x+150, y, w, h), 'red', 'blue', (50, 50))
  82.  
  83.  
  84. # test it ...
  85. app = wx.App(0)
  86. MyFrame(title='put some shapes on a canvas').Show()
  87. app.MainLoop()
Last edited by Ene Uran; Aug 4th, 2008 at 4:57 pm. Reason: added corner radius comment
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,297
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 178
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting wxPython (GUI code)

 
0
  #53
Aug 4th, 2008
I am surprised nobody has brought up the old wx.ListBox() widget yet. Well, here it is, a fun thing to experiment with (stole the name_list from vegaseat):
  1. # load, sort and clear a wxPython
  2. # wx.ListBox(parent, id, pos, size, choices, style)
  3.  
  4. import wx
  5.  
  6. class MyFrame(wx.Frame):
  7. def __init__(self, parent, mytitle, name_list):
  8. wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle)
  9. self.SetBackgroundColour("green")
  10. self.name_list = list(name_list)
  11.  
  12. self.listbox = wx.ListBox(self, wx.ID_ANY, choices=[])
  13. self.listbox.Bind(wx.EVT_LISTBOX, self.listboxClick)
  14.  
  15. # create action widgets
  16. self.load_button = wx.Button(self, wx.ID_ANY, "load ListBox")
  17. self.clear_button = wx.Button(self, wx.ID_ANY, "clear ListBox")
  18. self.sort_button = wx.Button(self, wx.ID_ANY, "sort ListBox")
  19. # bind mouse event to an action
  20. self.load_button.Bind(wx.EVT_BUTTON, self.load_buttonClick)
  21. self.clear_button.Bind(wx.EVT_BUTTON, self.clear_buttonClick)
  22. self.sort_button.Bind(wx.EVT_BUTTON, self.sort_buttonClick)
  23. # create an output widget
  24. self.label = wx.StaticText(self, wx.ID_ANY, "")
  25.  
  26. sizer = wx.GridBagSizer(vgap=5, hgap=5)
  27. # pos=(row, column) span=(rowspan, columnspan)
  28. # wx.ALL puts the specified border on all sides
  29. sizer.Add(self.load_button, pos=(0, 0), flag=wx.ALL, border=5)
  30. # listbox spans 6 rows and 2 columns
  31. sizer.Add(self.listbox, pos=(1, 0), span=(6, 2),
  32. flag=wx.ALL|wx.EXPAND, border=5)
  33. sizer.Add(self.clear_button, pos=(7, 1), flag=wx.ALL, border=5)
  34. sizer.Add(self.sort_button, pos=(7, 0), flag=wx.ALL, border=5)
  35. sizer.Add(self.label, pos=(8, 0), flag=wx.ALL, border=5)
  36. self.SetSizer(sizer)
  37.  
  38. # size the frame so all the widgets fit
  39. self.Fit()
  40.  
  41. def load_buttonClick(self, event):
  42. """load the name list into the bistbox"""
  43. # use self.listbox.Set(name_list) or ...
  44. for name in self.name_list:
  45. self.listbox.Append(name)
  46.  
  47. def clear_buttonClick(self, event):
  48. """clear all items from the listbox"""
  49. self.listbox.Clear()
  50. self.label.SetLabel("")
  51.  
  52. def sort_buttonClick(self, event):
  53. """sort the items in the listbox"""
  54. # GetItems() is new in wxPython2.8
  55. # puts the listbox items into a list
  56. name_list = self.listbox.GetItems()
  57. name_list.sort()
  58. # Set() clears and reloads the listbox
  59. self.listbox.Set(name_list)
  60.  
  61. def listboxClick(self, event):
  62. """display the selected ListBox item"""
  63. selected_item = self.listbox.GetStringSelection()
  64. s = "You selected " + selected_item
  65. self.label.SetLabel(s)
  66.  
  67.  
  68. name_list = [
  69. "Andreas",
  70. "Erich",
  71. "Udo",
  72. "Jens",
  73. "Bjorn",
  74. "Heidrun",
  75. "Klaus",
  76. "Ulla",
  77. "Volger",
  78. "Helmut",
  79. "Freja",
  80. "Larry",
  81. "Harry"
  82. ]
  83.  
  84. app = wx.App(0)
  85. # create the MyFrame instance and then show the frame
  86. MyFrame(None, 'listbox test', name_list).Show()
  87. app.MainLoop()
Last edited by sneekula; Aug 4th, 2008 at 10:46 pm. Reason: darn spelling
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,141
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 948
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting wxPython (GUI code)

 
0
  #54
Aug 7th, 2008
Thanks Snee for your nice wx.ListBox() example. There is a real high tech listbox in the gizmo section of wxPython. With this one you can edit a selected item including cut, copy, paste portions of it. You can delete, or move selected items up or down in the list. Additionally you can insert, write or paste a new item into the list. You simply have to test it out to get a feel of it ...
  1. # wxPython's amazing wx.gizmos.EditableListBox()
  2. # you can edit (also cut, copy, paste), delete, move selected
  3. # items up or down, and insert (also paste) a new item
  4. # tested with Python25 and wxPython28 vegaseat 07aug2008
  5.  
  6. import wx
  7. import wx.gizmos
  8.  
  9. class MyFrame(wx.Frame):
  10. def __init__(self, parent, mytitle, name_list):
  11. wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle)
  12. self.panel = wx.Panel(self, wx.ID_ANY)
  13. self.panel.SetBackgroundColour("green")
  14. self.name_list = list(name_list)
  15.  
  16. self.elistbox = wx.gizmos.EditableListBox(self.panel, wx.ID_ANY,
  17. label="List of Names")
  18. # get the actual control portion of the EditableListBox
  19. self.actual_listctrl = self.elistbox.GetListCtrl()
  20. # binds to any newly focused/selected item
  21. self.actual_listctrl.Bind(wx.EVT_LIST_ITEM_FOCUSED,
  22. self.listctrlClick)
  23.  
  24. # create action widgets
  25. load_button = wx.Button(self.panel, wx.ID_ANY, "load ListBox")
  26. clear_button = wx.Button(self.panel, wx.ID_ANY, "clear ListBox")
  27. sort_button = wx.Button(self.panel, wx.ID_ANY, "sort ListBox")
  28. # bind mouse click event to an action
  29. load_button.Bind(wx.EVT_BUTTON, self.load_buttonClick)
  30. clear_button.Bind(wx.EVT_BUTTON, self.clear_buttonClick)
  31. sort_button.Bind(wx.EVT_BUTTON, self.sort_buttonClick)
  32. # create an output widget
  33. self.label = wx.StaticText(self.panel, wx.ID_ANY, "")
  34.  
  35. sizer = wx.GridBagSizer(vgap=5, hgap=5)
  36. # pos=(row, column) span=(rowspan, columnspan)
  37. # wx.ALL puts the specified border on all sides
  38. sizer.Add(load_button, pos=(0, 0), flag=wx.ALL, border=5)
  39. # listbox spans 6 rows and 2 columns
  40. sizer.Add(self.elistbox, pos=(1, 0), span=(6, 2),
  41. flag=wx.ALL|wx.EXPAND, border=5)
  42. sizer.Add(clear_button, pos=(7, 1), flag=wx.ALL, border=5)
  43. sizer.Add(sort_button, pos=(7, 0), flag=wx.ALL, border=5)
  44. sizer.Add(self.label, pos=(8, 0), flag=wx.ALL, border=5)
  45. # set the sizer and fit all its widgets
  46. self.panel.SetSizerAndFit(sizer)
  47.  
  48. # size the frame so all its widgets fit inside
  49. self.Fit()
  50.  
  51. def load_buttonClick(self, event):
  52. """load the name list into the bistbox"""
  53. self.elistbox.SetStrings(name_list)
  54.  
  55. def clear_buttonClick(self, event):
  56. """clear all items from the elistbox"""
  57. self.elistbox.SetStrings([])
  58. self.label.SetLabel("")
  59.  
  60. def sort_buttonClick(self, event):
  61. """sort the items in the elistbox"""
  62. # GetStrings() puts the elistbox items into a list
  63. name_list = self.elistbox.GetStrings()
  64. name_list.sort()
  65. # SetStrings() clears and reloads the elistbox
  66. self.elistbox.SetStrings(name_list)
  67.  
  68. def listctrlClick(self, event):
  69. """display the selected listctrl item of the elistbox"""
  70. for n in range(self.actual_listctrl.GetItemCount()):
  71. state = wx.LIST_STATE_SELECTED
  72. if self.actual_listctrl.GetItemState(n, state):
  73. selected_item = self.actual_listctrl.GetItemText(n)
  74. s = "You selected " + selected_item
  75. self.label.SetLabel(s)
  76.  
  77.  
  78. name_list = [
  79. "Erich",
  80. "Udo",
  81. "Jens",
  82. "Bjorn",
  83. "Heidrun",
  84. "Klaus",
  85. "Zoe",
  86. "Ulla",
  87. "Volger",
  88. "Helmut",
  89. "Lisa",
  90. "Larry",
  91. "Andreas",
  92. "Harry"
  93. ]
  94.  
  95. app = wx.App(0)
  96. # create a MyFrame instance and show the frame
  97. MyFrame(None, 'elistbox test', name_list).Show()
  98. app.MainLoop()
Last edited by vegaseat; Aug 7th, 2008 at 12:08 pm. Reason: or
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,141
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 948
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting wxPython (GUI code)

 
0
  #55
Aug 8th, 2008
The wxPython GUI toolkit has the Open Graphics Library (OGL) integrated in its later versions. This avoids the often cumbersome download and installation of OGL. Here is an example how you can create a number of shapes and drag them around the canvas ...
  1. # the Open Graphics Library (OGL) is now part of wxPython
  2. # also test use of a custom class derived from ogl.PolygonShape
  3. # tested with Python25 and wxPython28 vegaseat 08aug2008
  4.  
  5. import wx
  6. import wx.lib.ogl as ogl
  7.  
  8. class MyFrame(wx.Frame):
  9. def __init__(self):
  10. wx.Frame.__init__( self, None, wx.ID_ANY,
  11. "wx.lib.ogl Demo2", size=(400,300))
  12.  
  13. canvas = ogl.ShapeCanvas(self)
  14. canvas.SetBackgroundColour("yellow")
  15.  
  16. diagram = ogl.Diagram()
  17. # marry the two ...
  18. canvas.SetDiagram(diagram)
  19. diagram.SetCanvas(canvas)
  20.  
  21. # draw some standard shapes ...
  22. # (check how creation order affects overlap)
  23. circle = ogl.CircleShape(80.0) # radius
  24. circle.SetX(125.0) # center x
  25. circle.SetY(125.0)
  26. # use preset pen and brush types
  27. # border ...
  28. circle.SetPen(wx.RED_PEN)
  29. # fill ...
  30. circle.SetBrush(wx.GREEN_BRUSH)
  31. canvas.AddShape(circle)
  32.  
  33. rectangle = ogl.RectangleShape(100, 80) # (w, h)
  34. rectangle.SetX(55.0) # center x
  35. rectangle.SetY(45.0) # center y
  36. # use wx.Pen and wx.Brush for more options
  37. # wx.Pen(colour, width=1, style=wx.SOLID)
  38. # also wx.DOT, wx.DOT_DASH, wx.TRANSPARENT --> no border
  39. rectangle.SetPen(wx.Pen("blue", 2))
  40. # wxBrush(colour, style=wx.SOLID)
  41. # also wx.CROSS_HATCH, wx.CROSSDIAG_HATCH, wx.TRANSPARENT
  42. rectangle.SetBrush(wx.Brush("blue", wx.CROSSDIAG_HATCH))
  43. canvas.AddShape(rectangle)
  44.  
  45. text = ogl.TextShape(250, 30) # (w, h)
  46. text.SetX(180) # center x
  47. text.SetY(240)
  48. text.AddText("you can drag the shapes or the text")
  49. canvas.AddShape(text)
  50.  
  51. # if you have an image file
  52. # you can also create a shape with the image
  53. image_file = 'victory.jpg'
  54. bmp = wx.Bitmap(image_file)
  55. picture = ogl.BitmapShape()
  56. picture.SetBitmap(bmp)
  57. picture.SetX(330) # center x
  58. picture.SetY(160)
  59. canvas.AddShape(picture)
  60.  
  61. # use the custom class ...
  62. circle = DiamondShape(130, 100) # (w, h)
  63. circle.SetX(225.0) # center x
  64. circle.SetY(70.0)
  65. circle.SetPen(wx.BLACK_PEN)
  66. # use no fill ...
  67. circle.SetBrush(wx.TRANSPARENT_BRUSH)
  68. canvas.AddShape(circle)
  69.  
  70. # all the shapes are in, so show them
  71. diagram.ShowAll(True)
  72.  
  73. # use a sizer
  74. sizer = wx.BoxSizer(wx.VERTICAL)
  75. # canvas will grow as frame is stretched
  76. sizer.Add(canvas, 1, wx.GROW)
  77. self.SetSizer(sizer)
  78.  
  79.  
  80. class DiamondShape(ogl.PolygonShape):
  81. """create a diamond shaped object using a polygon"""
  82. def __init__(self, w=60.0, h=60.0):
  83. ogl.PolygonShape.__init__(self)
  84. points = [(0, -h/2.0), (w/2.0, 0), (0,h/2.0), (-w/2.0, 0)]
  85. self.Create(points)
  86.  
  87.  
  88. app = wx.App(0)
  89. ogl.OGLInitialize()
  90. MyFrame().Show()
  91. app.MainLoop()
Last edited by vegaseat; Aug 8th, 2008 at 4:23 pm. Reason: notes
Attached Images
 
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,141
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 948
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting wxPython (GUI code)

 
0
  #56
Aug 8th, 2008
To allow just one instance of your wxPython program to run, you need to modify your application class slightly ...
  1. # allow only one instance of a wxPython program to run
  2.  
  3. import wx
  4.  
  5. class MyFrame(wx.Frame):
  6. def __init__(self,parent, mytitle):
  7. wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle,
  8. size=(300, 90))
  9. self.SetBackgroundColour("red")
  10. self.Centre()
  11. # more of your program code here ...
  12.  
  13.  
  14. class SingleApp(wx.App):
  15. def OnInit(self):
  16. name = "SingleApp-%s" % (wx.GetUserId())
  17. self.instance = wx.SingleInstanceChecker(name)
  18. # create a title
  19. mytitle = name
  20. if self.instance.IsAnotherRunning():
  21. message = "Another instance of %s is running" % mytitle
  22. wx.MessageBox(message, "Error")
  23. return False
  24. MyFrame(None, mytitle).Show()
  25. return True
  26.  
  27.  
  28. app = SingleApp()
  29. app.MainLoop()
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,141
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 948
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting wxPython (GUI code)

 
0
  #57
Aug 9th, 2008
Radio buttons give you a fixed input, one choice at a time. If you have a series of radio buttons it's easiest to group them together with a wx.RadioBox(). The code example shows you how to do this, and also is a good example for the wx.BoxSizer() layout manager ...
  1. # test the wx.RadioBox() widget
  2. # wx.RadioBox(parent, id, label, pos, size, choices, majorDimension, style)
  3. # combines a wx.StaticBox() with a wx.RadioButton()
  4. # only one radiobutton can be selected at a time in the radiobox
  5.  
  6. import wx
  7.  
  8. class MyFrame(wx.Frame):
  9. def __init__(self, parent, mytitle):
  10. wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle)
  11. self.SetBackgroundColour("yellow")
  12.  
  13. # create input widgets
  14. self.options1 = ['now', 'later', 'much later', 'never']
  15. self.radiobox1 = wx.RadioBox(self, wx.ID_ANY,
  16. " Select one option ",
  17. choices=self.options1, style=wx.VERTICAL)
  18. # set radio button 1 as selected (first button is 0)
  19. self.radiobox1.SetSelection(1)
  20. # bind mouse click to an action
  21. self.radiobox1.Bind(wx.EVT_RADIOBOX, self.onAction)
  22.  
  23. self.options2 = ['blue', 'red', 'yellow', 'orange', 'green',
  24. 'purple', 'navy blue', 'black', 'gray']
  25. # this radio box has 3 columns
  26. self.radiobox2 = wx.RadioBox(self, wx.ID_ANY,
  27. label=" What color would you like? ",
  28. choices=self.options2,
  29. majorDimension=3,
  30. style=wx.RA_SPECIFY_COLS)
  31. self.radiobox2.SetSelection(0)
  32. self.radiobox2.Bind(wx.EVT_RADIOBOX, self.onAction)
  33.  
  34. # create output widgets
  35. self.label1 = wx.StaticText(self, wx.ID_ANY, "" )
  36. self.label2 = wx.StaticText(self, wx.ID_ANY, "" )
  37.  
  38. # use box sizers to layout widgets
  39. # the two vertical sizers nest in the horizontal sizer
  40. sizer_v1 = wx.BoxSizer(wx.VERTICAL)
  41. sizer_v2 = wx.BoxSizer(wx.VERTICAL)
  42. sizer_h = wx.BoxSizer(wx.HORIZONTAL)
  43. # add the widgets to the corresponding vertical sizer
  44. sizer_v1.Add(self.radiobox1, 0, flag=wx.ALL, border=10)
  45. sizer_v1.Add(self.label1, 0, wx.ALL, 10)
  46. sizer_v2.Add(self.radiobox2, 0, wx.ALL, 10)
  47. # add a spacer (optional) ...
  48. sizer_v2.Add((0, 0), 0, wx.ALL, 10)
  49. sizer_v2.Add(self.label2, 0, wx.ALL, 10)
  50. # put the 2 vertical sizers into the horizontal sizer
  51. sizer_h.Add(sizer_v1, 0)
  52. sizer_h.Add(sizer_v2, 0)
  53. # it's the horizontal sizer you have to set
  54. # also fit the frame snuggly around the whole thing
  55. self.SetSizerAndFit(sizer_h)
  56.  
  57. # show present selection
  58. self.onAction(None)
  59.  
  60. def onAction(self, event):
  61. """show the selected choice"""
  62. index1 = self.radiobox1.GetSelection()
  63. s = "Choice = " + self.options1[index1]
  64. self.label1.SetLabel(s)
  65. # dito for radio box #2
  66. index2 = self.radiobox2.GetSelection()
  67. s = "Choice = " + self.options2[index2]
  68. self.label2.SetLabel(s)
  69.  
  70.  
  71.  
  72. app = wx.App(0)
  73. # create a MyFrame instance and show the frame
  74. MyFrame(None, 'testing wx.RadioBox()').Show()
  75. app.MainLoop()
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,141
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 948
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting wxPython (GUI code)

 
0
  #58
Aug 10th, 2008
You can also create a radio-button like behaviour in a menu using radio-items. Take a look at this menu example ...
  1. # experimenting with wxPython's wx.Menu()
  2.  
  3. import wx
  4.  
  5. # some needed unique ids for the radio item menu
  6. ID_RED = 1001
  7. ID_GREEN = 1002
  8. ID_BLUE = 1003
  9. ID_YELLOW = 1004
  10. ID_WHITE = 1005
  11.  
  12. class MyFrame(wx.Frame):
  13. def __init__(self):
  14. wx.Frame.__init__(self, None, wx.ID_ANY,
  15. 'Click on a menubar item', size=(300, 350))
  16.  
  17. # create a status bar at the bottom
  18. self.CreateStatusBar()
  19. self.SetStatusText("This is the statusbar")
  20.  
  21. self.createMenu()
  22.  
  23. def createMenu(self):
  24. """creates all the menu items"""
  25. filemenu = wx.Menu()
  26. filemenu_save = filemenu.Append(wx.ID_ANY, "&Save",
  27. "Save something to file (just a dummy)")
  28. filemenu.AppendSeparator()
  29. filemenu_exit = filemenu.Append(wx.ID_ANY, "E&xit",
  30. "Quit the program")
  31.  
  32. optionmenu = wx.Menu()
  33. self.optionmenu = optionmenu
  34. optionmenu.AppendRadioItem(ID_RED, "red", "")
  35. optionmenu.AppendRadioItem(ID_GREEN, "green", "")
  36. optionmenu.AppendRadioItem(ID_BLUE, "blue", "")
  37. optionmenu.AppendRadioItem(ID_YELLOW, "yellow", "")
  38. optionmenu.AppendRadioItem(ID_WHITE, "white", "")
  39.  
  40. helpmenu = wx.Menu()
  41. # the optional & allows you to use alt/a
  42. # the last string argument shows in the status bar
  43. # on mouse_over
  44. helpmenu_about = helpmenu.Append(wx.ID_ANY, "&About",
  45. "About message")
  46.  
  47. # create a menu bar at the top for the menu titles
  48. menuBar = wx.MenuBar()
  49. menuBar.Append(filemenu, "&File")
  50. menuBar.Append(optionmenu, "&Option")
  51. menuBar.Append(helpmenu, "&Help")
  52. self.SetMenuBar(menuBar)
  53.  
  54. # bind the menu events to an action method
  55. self.Bind(wx.EVT_MENU, self.onMenuAbout, helpmenu_about)
  56. self.Bind(wx.EVT_MENU, self.onMenuSave, filemenu_save)
  57. self.Bind(wx.EVT_MENU, self.onMenuExit, filemenu_exit)
  58. """
  59. self.Bind(wx.EVT_MENU, self.onMenuColor, id=ID_RED)
  60. self.Bind(wx.EVT_MENU, self.onMenuColor, id=ID_GREEN)
  61. self.Bind(wx.EVT_MENU, self.onMenuColor, id=ID_BLUE)
  62. self.Bind(wx.EVT_MENU, self.onMenuColor, id=ID_YELLOW)
  63. self.Bind(wx.EVT_MENU, self.onMenuColor, id=ID_WHITE)
  64. """
  65. # better give id range ...
  66. self.Bind(wx.EVT_MENU_RANGE, self.onMenuColor, id=ID_RED,
  67. id2=ID_WHITE)
  68.  
  69. # set the preselected colour
  70. self.onMenuColor(self)
  71.  
  72. def onMenuAbout(self, event):
  73. dlg = wx.MessageDialog(self,
  74. "a simple application using wxFrame, wxMenu\n"
  75. "a statusbar, and this about message.",
  76. "About", wx.OK|wx.ICON_INFORMATION)
  77. dlg.ShowModal()
  78. dlg.Destroy()
  79.  
  80. def onMenuSave(self, event):
  81. self.SetStatusText("Not implemented yet!")
  82.  
  83. def onMenuColor(self, event):
  84. for item in self.optionmenu.GetMenuItems():
  85. #print item, item.IsChecked(), item.GetLabel() # test
  86. if item.IsChecked():
  87. # establish new color
  88. self.SetBackgroundColour(item.GetLabel())
  89. # now clear old color and set to new color
  90. self.ClearBackground()
  91.  
  92. def onMenuExit(self, event):
  93. # exit via wx.EVT_CLOSE event
  94. self.Close(True)
  95.  
  96. app = wx.App(0)
  97. # create class instance
  98. MyFrame().Show()
  99. # start the event loop
  100. app.MainLoop()
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,297
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 178
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting wxPython (GUI code)

 
0
  #59
Aug 11th, 2008
The wx.grid.Grid() widget lets you present tabular data in an organized fashion, very similar to the popular spreadsheet programs. Here is a short example of it's use:
  1. # a practical use of wxPython's wx.grid.Grid() widget
  2. # load the grid via a list of lists
  3. # bind cell select (mouse left click)
  4.  
  5. import wx
  6. import wx.grid
  7.  
  8. class MyGrid(wx.grid.Grid):
  9. def __init__(self, parent, data_list):
  10. wx.grid.Grid.__init__(self, parent, wx.ID_ANY)
  11. self.parent = parent
  12.  
  13. # set the rows and columns the grid needs
  14. self.rows = len(data_list)
  15. self.cols = len(data_list[0])
  16. self.CreateGrid(self.rows, self.cols)
  17.  
  18. # set some column widths (default is 80) different
  19. self.SetColSize(0, 180)
  20. self.SetColSize(3, 100)
  21. self.SetRowLabelSize(40) # sets leading row width
  22.  
  23. # set column lable titles at the top
  24. for ix, title in enumerate(data_list[0]):
  25. self.SetColLabelValue(ix, title)
  26.  
  27. # create reusable attribute objects
  28. self.attr = wx.grid.GridCellAttr()
  29. self.attr.SetTextColour('black')
  30. self.attr.SetBackgroundColour('yellow')
  31. #self.attr.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL))
  32.  
  33. # select the cell with a mouse left click
  34. self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.onCellLeftClick)
  35.  
  36. self.loadCells(data_list)
  37.  
  38. def onCellLeftClick(self, event):
  39. row = event.GetRow()
  40. col = event.GetCol()
  41. self.parent.SetTitle("row=%d col=%d value=%s" %
  42. (row, col, self.GetCellValue(row, col)))
  43. # move the grid's cursor to frame the cell
  44. self.SetGridCursor(row, col)
  45.  
  46. def loadCells(self, data_list):
  47. # note that title row is taken
  48. for row in range(1, self.rows):
  49. # set cell attributes for the whole row
  50. self.SetRowAttr(row-1, self.attr)
  51. for col in range(self.cols):
  52. value = data_list[row][col]
  53. self.SetCellValue(row-1, col, value)
  54. self.SetReadOnly(row-1, col, True)
  55. if col > 0:
  56. self.SetCellAlignment(row-1, col,
  57. wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
  58.  
  59. self.SetCellTextColour(row, 0, 'red')
  60. self.SetCellBackgroundColour(row, 0, 'white')
  61. self.SetCellFont(row, 0, wx.Font(8, wx.ROMAN, wx.ITALIC, wx.NORMAL))
  62. honor = "University of Detroit Chemistry Department"
  63. self.SetCellValue(row, 0, honor)
  64.  
  65.  
  66. # build the data_list, raw_data string is from a csv file ...
  67. raw_data = """\
  68. Solvent Name, BP (deg C), MP (deg C), Density (g/ml)
  69. ACETIC ACID,117.9,16.7,1.049
  70. ACETIC ANHYDRIDE,140.1,-73.1,1.087
  71. ACETONE,56.3,-94.7,0.791
  72. ACETONITRILE,81.6,-43.8,0.786
  73. ANISOLE,154.2,-37,0.995
  74. BENZYL ALCOHOL,205.4,-15.3,1.045
  75. BENZYL BENZOATE,323.5,19.4,1.112
  76. BUTYL ALCOHOL NORMAL,117.7,-88.6,0.81
  77. BUTYL ALCOHOL SEC,99.6,-114.7,0.805
  78. BUTYL ALCOHOL TERTIARY,82.2,25.5,0.786
  79. CHLOROBENZENE,131.7,-45.6,1.111
  80. CYCLOHEXANE,80.7,6.6,0.779
  81. CYCLOHEXANOL,161.1,25.1,0.971
  82. CYCLOHEXANONE,155.2,-47,0.947
  83. DICHLOROETHANE 1 2,83.5,-35.7,1.246
  84. DICHLOROMETHANE,39.8,-95.1,1.325
  85. DIETHYL ETHER,34.5,-116.2,0.715
  86. DIMETHYLACETAMIDE,166.1,-20,0.937
  87. DIMETHYLFORMAMIDE,153.3,-60.4,0.944
  88. DIMETHYLSULFOXIDE,189.4,18.5,1.102
  89. DIOXANE 1 4,101.3,11.8,1.034
  90. DIPHENYL ETHER,258.3,26.9,1.066
  91. ETHYL ACETATE,77.1,-83.9,0.902
  92. ETHYL ALCOHOL,78.3,-114.1,0.789
  93. ETHYL DIGLYME,188.2,-45,0.906
  94. ETHYLENE CARBONATE,248.3,36.4,1.321
  95. ETHYLENE GLYCOL,197.3,-13.2,1.114
  96. FORMIC ACID,100.6,8.3,1.22
  97. HEPTANE,98.4,-90.6,0.684
  98. HEXAMETHYL PHOSPHORAMIDE,233.2,7.2,1.027
  99. HEXANE,68.7,-95.3,0.659
  100. ISO OCTANE,99.2,-107.4,0.692
  101. ISOPROPYL ACETATE,88.6,-73.4,0.872
  102. ISOPROPYL ALCOHOL,82.3,-88,0.785
  103. METHYL ALCOHOL,64.7,-97.7,0.791
  104. METHYL ETHYLKETONE,79.6,-86.7,0.805
  105. METHYL ISOBUTYL KETONE,116.5,-84,0.798
  106. METHYL T-BUTYL ETHER,55.5,-10,0.74
  107. METHYLPYRROLIDINONE N,203.2,-23.5,1.027
  108. MORPHOLINE,128.9,-3.1,1
  109. NITROBENZENE,210.8,5.7,1.208
  110. NITROMETHANE,101.2,-28.5,1.131
  111. PENTANE,36.1, -129.7,0.626
  112. PHENOL,181.8,40.9,1.066
  113. PROPANENITRILE,97.1,-92.8,0.782
  114. PROPIONIC ACID,141.1,-20.7,0.993
  115. PROPIONITRILE,97.4,-92.8,0.782
  116. PROPYLENE GLYCOL,187.6,-60.1,1.04
  117. PYRIDINE,115.4,-41.6,0.978
  118. SULFOLANE,287.3,28.5,1.262
  119. TETRAHYDROFURAN,66.2,-108.5,0.887
  120. TOLUENE,110.6,-94.9,0.867
  121. TRIETHYL PHOSPHATE,215.4,-56.4,1.072
  122. TRIETHYLAMINE,89.5,-114.7,0.726
  123. TRIFLUOROACETIC ACID,71.8,-15.3,1.489
  124. WATER,100,0,1
  125. XYLENES,139.1,-47.8,0.86"""
  126.  
  127. data_list = []
  128. for line in raw_data.split('\n'):
  129. line_list = line.split(',')
  130. data_list.append(line_list)
  131.  
  132.  
  133. app = wx.App(0)
  134. # create a window/frame, no parent, use a default ID
  135. title = "test the wx.grid.Grid()"
  136. frame = wx.Frame(None, wx.ID_ANY, title, size=(520, 360))
  137. # create the class instance
  138. mygrid = MyGrid(frame, data_list)
  139. frame.Show(True)
  140. app.MainLoop()
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,141
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 948
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting wxPython (GUI code)

 
1
  #60
Aug 11th, 2008
Very nice contribution of a spreadsheet like grid Snee!

If you ever have to present a lot of widgets on a limited space, the wx.NoteBook() widget is a great solution. In this case, I used it for a distance, area and volume conversion program. A start at least, generic enough so more conversions can easily be added. Just tab your way through the pages ...
  1. # experiments with wxPython's wx.Notebook() widget
  2. # converting distance, area and volume units
  3. # tested with Python25 and wxPython28 by vegaseat 11aug2008
  4.  
  5. import wx
  6.  
  7. class MyNotebook(wx.Frame):
  8. def __init__(self, parent, title, distD, areaD, volD):
  9. wx.Frame.__init__(self, parent, wx.ID_ANY, title,
  10. size=(460, 360))
  11.  
  12. # style=wx.NB_TOP is default
  13. # could use style=wx.NB_BOTTOM
  14. nb = wx.Notebook(self, wx.ID_ANY)
  15. # MyPage(parent, conversion dictionary, preselected choice)
  16. self.page1 = MyPage(nb, distD, 3)
  17. self.page2 = MyPage(nb, areaD, 2)
  18. self.page3 = MyPage(nb, volD, 0)
  19. nb.AddPage(self.page1, "Distance Conversion")
  20. nb.AddPage(self.page2, "Area Conversion")
  21. nb.AddPage(self.page3, "Volume Conversion")
  22. # start with page1 active
  23. self.page1.SetFocus()
  24.  
  25. class MyPage(wx.Panel):
  26. """
  27. each panel instance creates the notbook page content
  28. from the given conversion dictionary convD
  29. """
  30. def __init__(self, parent, convD, preselect):
  31. wx.Panel.__init__(self, parent, wx.ID_ANY)
  32. oatmeal3 = '#FCFFE1'
  33. self.SetBackgroundColour(oatmeal3)
  34.  
  35. self.convD = convD
  36.  
  37. # create list of possible units
  38. self.options = convD.keys()
  39.  
  40. self.radiobox1 = wx.RadioBox(self, wx.ID_ANY,
  41. "Select a unit to convert from",
  42. choices=self.options, style=wx.VERTICAL)
  43. # set radio button 1 as selected (first button is 0)
  44. self.radiobox1.SetSelection(preselect)
  45. # bind mouse click to an action
  46. self.radiobox1.Bind(wx.EVT_RADIOBOX, self.onAction)
  47.  
  48. self.radiobox2 = wx.RadioBox(self, wx.ID_ANY,
  49. "Select a unit to convert to ",
  50. choices=self.options, style=wx.VERTICAL)
  51. # set radio button 1 as selected (first button is 0)
  52. self.radiobox2.SetSelection(preselect)
  53. # bind mouse click to an action
  54. self.radiobox2.Bind(wx.EVT_RADIOBOX, self.onAction)
  55.  
  56. # additional widgets
  57. self.label1 = wx.StaticText(self, wx.ID_ANY, "" )
  58. self.label2 = wx.StaticText(self, wx.ID_ANY, "" )
  59.  
  60. self.edit1 = wx.TextCtrl(self, wx.ID_ANY, value="1.0",
  61. size=(150, 20))
  62. # respond to enter key when focus is on edit1
  63. self.edit1.Bind(wx.EVT_TEXT_ENTER, self.onAction)
  64. self.edit2 = wx.TextCtrl(self, wx.ID_ANY, value="",
  65. size=(150, 20))
  66.  
  67. self.button = wx.Button(self, wx.ID_ANY, label='Convert')
  68. self.button.Bind(wx.EVT_BUTTON, self.onAction)
  69.  
  70. # use box sizers to layout the widgets
  71. # nest the 3 vertical sizers in the horizontal sizer later
  72. sizer_v1 = wx.BoxSizer(wx.VERTICAL)
  73. sizer_v2 = wx.BoxSizer(wx.VERTICAL)
  74. sizer_v3 = wx.BoxSizer(wx.VERTICAL)
  75. sizer_h = wx.BoxSizer(wx.HORIZONTAL)
  76. # add the widgets to the corresponding vertical sizer
  77. sizer_v1.Add(self.radiobox1, 0, flag=wx.ALL, border=10)
  78. sizer_v1.Add(self.label1, 0, wx.LEFT|wx.RIGHT|wx.TOP, 10)
  79. sizer_v1.Add(self.edit1, 0, wx.LEFT|wx.RIGHT, 10)
  80. # add a spacer to position the button lower ...
  81. sizer_v2.Add((0, 225), 0, wx.ALL, 10)
  82. sizer_v2.Add(self.button, 0, wx.ALL, 10)
  83. sizer_v3.Add(self.radiobox2, 0, wx.ALL, 10)
  84. sizer_v3.Add(self.label2, 0, wx.LEFT|wx.RIGHT|wx.TOP, 10)
  85. sizer_v3.Add(self.edit2, 0, wx.LEFT|wx.RIGHT, 10)
  86. # put the 3 vertical sizers into the horizontal sizer
  87. sizer_h.Add(sizer_v1, 0)
  88. sizer_h.Add(sizer_v2, 0)
  89. sizer_h.Add(sizer_v3, 0)
  90. # it's the horizontal sizer you have to set
  91. self.SetSizer(sizer_h)
  92.  
  93. # show present selection
  94. self.onAction(None)
  95.  
  96. def onAction(self, event):
  97. """show the selected choice"""
  98. index1 = self.radiobox1.GetSelection()
  99. unit1 = self.options[index1]
  100. #print unit1 # test
  101. s = "Enter a value (%s):" % unit1
  102. self.label1.SetLabel(s)
  103. # dito for radio box #2
  104. index2 = self.radiobox2.GetSelection()
  105. unit2 = self.options[index2]
  106. #print unit2 # test
  107. s = "Result (%s):" % unit2
  108. self.label2.SetLabel(s)
  109.  
  110. value = float(self.edit1.GetValue())
  111. factor1 = self.convD[unit1]
  112. factor2 = self.convD[unit2]
  113. result = factor2 * value/factor1
  114. self.edit2.ChangeValue(str(result))
  115.  
  116.  
  117. # these are the conversion dictionaries ...
  118. # (note that units won't appear in that order)
  119. distD ={}
  120. # all scale factors are relative to the first unit below
  121. distD['meter'] = 1.0
  122. distD['micron'] = 1000000.0
  123. distD['millimeter'] = 1000.0
  124. distD['centimeter'] = 100.0
  125. distD['kilometer'] = 0.001
  126. distD['inch'] = 100.0/2.54
  127. distD['foot'] = 100.0/30.48
  128. distD['yard'] = 100.0/91.44
  129. distD['mile'] = 0.001/1.609344
  130. distD['rod'] = 1.0/5.029
  131.  
  132. areaD = {}
  133. # all scale factors are relative to the first unit below
  134. areaD['sq meter'] = 1.0
  135. areaD['sq millimeter'] = 1000000.0
  136. areaD['sq centimeter'] = 10000.0
  137. areaD['sq kilometer'] = 0.000001
  138. areaD['hectare'] = 0.0001
  139. areaD['sq inch'] = 1550.003
  140. areaD['sq foot'] = 10.76391
  141. areaD['sq yard'] = 1.19599
  142. areaD['acre'] = 0.0002471054
  143. areaD['sq mile'] = 0.0000003861022
  144.  
  145. volD = {}
  146. # all scale factors are relative to the first unit below
  147. volD['cubic meter'] = 1.0
  148. volD['microliter'] = 1000000000.0
  149. volD['milliliter'] = 1000000.0
  150. volD['liter'] = 1000.0
  151. volD['pint(US)'] = 2113.376
  152. volD['quart(US)'] = 1056.688
  153. volD['gallon(US)'] = 264.172
  154. volD['cubic inch'] = 61023.74
  155. volD['cubic foot'] = 35.31467
  156. volD['cubic yard'] = 1.307951
  157.  
  158.  
  159. app = wx.App(1)
  160. MyNotebook(None, "testing wx.Notebook()", distD, areaD, volD).Show()
  161. app.MainLoop()
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Reply

Tags
examples, gui, python, wxpython

Message:



Similar Threads
Other Threads in the Python Forum


Views: 50800 | Replies: 130
Thread Tools Search this Thread



Tag cloud for examples, gui, python, wxpython
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC