Starting wxPython (GUI code)

Reply

Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting wxPython (GUI code)

 
1
  #121
Sep 16th, 2009
Just an experiment to explore the use of wxPython buttons to start and stop a process ...
  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()
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 1
Reputation: alexLand is an unknown quantity at this point 
Solved Threads: 0
alexLand alexLand is offline Offline
Newbie Poster

excellent!

 
0
  #122
Sep 17th, 2009
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.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,275
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting wxPython (GUI code)

 
1
  #123
Sep 17th, 2009
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:
  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()
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting wxPython (GUI code)

 
1
  #124
Sep 20th, 2009
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 ...
  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()
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Rainbow text

 
1
  #125
30 Days Ago
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 ...
  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
wx_rainbow.jpg  
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite
 
1
  #126
26 Days Ago
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 ...
  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()
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,275
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven
 
2
  #127
15 Days Ago
Just testing wxPython's wx.TextCtrl widget used as an edit field for input and output of text based data:
  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; 15 Days Ago at 3:31 pm.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Reply

Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC