| | |
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)
# explore WxPython buttons to start and stop a process # set flag to 'stop' to allow exit import wx class MyFrame(wx.Frame): def __init__(self, parent, mytitle): wx.Frame.__init__(self, parent, -1, mytitle, size=(300, 200)) self.SetBackgroundColour("yellow") self.start_btn = wx.Button(self, -1, label='Start') self.start_btn.Bind(wx.EVT_BUTTON, self.start_btnClick) self.stop_btn = wx.Button(self, -1, label='Stop') self.stop_btn.Bind(wx.EVT_BUTTON, self.stop_btnClick) self.label = wx.StaticText(self, -1, "-------") # layout the widgets in a vertical order sizer_v = wx.BoxSizer(wx.VERTICAL) # Add(widget, proportion, flag, border) sizer_v.Add(self.start_btn, 0, flag=wx.ALL, border=10) sizer_v.Add(self.stop_btn, 0, flag=wx.ALL, border=10) sizer_v.Add(self.label, 0, flag=wx.ALL, border=10) self.SetSizer(sizer_v) self.char = '>' def start_btnClick(self, event): self.flag = 'start' self.processing() def stop_btnClick(self, event): self.flag = 'stop' self.processing() def processing(self): self.SetTitle(self.flag) while True: if self.flag == 'stop': break if self.flag == 'start': self.label.SetLabel(self.char) # needed to keep other processes going wx.GetApp().Yield() wx.Sleep(1) self.char += '>' app = wx.App(0) MyFrame(None, 'start and stop').Show() app.MainLoop()
May 'the Google' be with you!
•
•
Join Date: Jun 2008
Posts: 1
Reputation:
Solved Threads: 0
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.
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)
# exploring wxPython's wx.grid.Grid() # load grid via a '(row, col): value' dictionary and a table class # that inherits and applies wx.grid.PyGridTableBase # snee import wx import wx.grid class MyFrame(wx.Frame): def __init__(self, header_list, data_dict): wx.Frame.__init__(self, None, wx.ID_ANY, title="ACME Inc. Staff Stats", size=(510,200)) self.grid = wx.grid.Grid(self) self.grid.SetRowLabelSize(30) # sets leading row width self.grid.SetDefaultRowSize(20) # sets all row height self.grid.SetColLabelSize(30) # sets leading col height self.grid.SetDefaultColSize(80) # sets all col width # select the cell with a mouse left click self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.cell_click) # the table takes care of all the grid stuff table = MyTable(header_list, data_dict) self.grid.SetTable(table, True) # optional, calculate rows of data needed for fun stats self.rows = max(data_dict.keys())[0] + 1 def cell_click(self, event): """cell has been left clicked""" row = event.GetRow() col = event.GetCol() # move the grid's cursor to frame the cell self.grid.SetGridCursor(row, col) # you can do some fun stats with the numbers num = [] if col > 0: #num = [] for nrow in range(self.rows): num.append(float(self.grid.GetCellValue(nrow, col))) val = self.grid.GetCellValue(row, col) if num: sf = "r%dc%d %s max=%.1f min=%.1f avg=%.1f" % \ (row, col, val, max(num), min(num), sum(num)/nrow) else: sf = "r%dc%d %s" % (row, col, val) self.SetTitle(sf) class MyTable(wx.grid.PyGridTableBase): def __init__(self, header_list, data_dict): wx.grid.PyGridTableBase.__init__(self) self.data = data_dict # calculate rows and cols needed to fit the data self.rows = max(data_dict.keys())[0] + 1 self.cols = max(data_dict.keys())[1] + 1 #print self.rows, self.cols # test # label lists have to match row and column numbers # default for self.rowLabels = ["1", "2", "3", "4", "5", ...] # default for self.colLabels = ["A", "B", "C", "D", "E", ...] # however, we have custom column labels self.colLabels = header_list # these are the five required methods ... def GetNumberRows(self): """actually sets number of rows""" return self.rows def GetNumberCols(self): """actually sets number of cols""" return self.cols def IsEmptyCell(self, row, col): return self.data.get((row, col)) is not None def GetValue(self, row, col): """actually sets value of each (row, col)""" value = self.data.get((row, col)) if value is not None: return value else: return '' def SetValue(self, row, col, value): self.data[(row,col)] = value # optional methods ... # allows the table to provide the attributes for each cell def GetAttr(self, row, col, kind): attr = wx.grid.GridCellAttr() attr.SetTextColour("black") attr.SetBackgroundColour("yellow") attr.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL)) return attr def GetColLabelValue(self, col): """you need to supply colLabels a list of labels""" return self.colLabels[col] '''not needed, used default row labels here def GetRowLabelValue(self, row): """you need to supply rowLabels a list of labels""" return self.rowLabels[row] ''' header_list = ['Name', 'Age', 'Weight', 'Pay', 'Golf', 'Bowl'] # raw data string could be from a csv file ... # columns are Name, Age, Weight, Pay, Golf avg, Bowling avg raw_data = """\ Albert, 45, 230, 96000, 67, 210 Curt, 22, 156, 34000, 56, 180 Doris, 19, 112, 27000, 79, 133 Larry, 34, 188, 57500, 49, 189 Lupe, 24, 134, 42000, 83, 224 Mark, 23, 202, 32000, 47, 201 Rita, 22, 96, 23500, 87, 102 Willy, 28, 286, 18000, 58, 134 Zoe, 19, 120, 39000, 63, 156""" # create a list of lists data_list = [] for line in raw_data.split('\n'): line_list = line.split(',') data_list.append(line_list) #print(data_list) # test # create a dictionary of (row, col):value pairs data_dict = {} for row, item in enumerate(data_list): #print row, item for col, value in enumerate(item): data_dict[(row, col)] = value #print(data_dict) # test app = wx.App(0) MyFrame(header_list, data_dict).Show() app.MainLoop()
No one died when Clinton lied.
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)
# using wxPython's wx.lib.plot.PlotCanvas() # to show a line graph of some stock values # tested with Python25 and wxPython28 # vegaseat import wx import wx.lib.plot import urllib2 class MyFrame(wx.Frame): def __init__(self, data_list, start_date, end_date, ticker, max_val, min_val): wx.Frame.__init__(self, parent=None, id=-1, title="line graph of stock values", size=(600, 300)) # set up the plotting canvas plot_canvas = wx.lib.plot.PlotCanvas(self) # get client usable size of frame frame_size = self.GetClientSize() # needed for SaveFile() later plot_canvas.SetInitialSize(size=frame_size) # optional allow scrolling plot_canvas.SetShowScrollbars(True) # optional drag/draw rubberband area to zoom # doubleclick to return to original # right click to shrink plot_canvas.SetEnableZoom(True) # optional # set the tick and axis label font size (default is 10 point) plot_canvas.SetFontSizeAxis(point=8) # set title font size (default is 15 point) plot_canvas.SetFontSizeTitle(point=10) # connect (x, y) points in data list with a line val_line = wx.lib.plot.PolyLine(data_list, colour='blue', width=1) # assign lines, title and axis labels title = "Latest 300 trading days of %s" % ticker x_axis = "Starting %s up to %s" % (start_date, end_date) y_axis = "value at close ($)" gc = wx.lib.plot.PlotGraphics([val_line], title, x_axis, y_axis) # draw the plot and set x and y axis sizes plot_canvas.Draw(gc, xAxis=(1, 300), yAxis=(min_val, max_val)) # optional save graph to an image file plot_canvas.SaveFile(fileName='stock1.jpg') ticker = "MSFT" sf = 'http://ichart.finance.yahoo.com/table.csv?s=%s' % ticker url = urllib2.urlopen(sf) # read 17000 bytes or about the last 300+ days data = url.readlines(17000) data_lines = [line.rstrip().split(',') for line in data] end_date = data_lines[1][0] start_date = data_lines[301][0] # look at the latest 300 trading days # and build a list of (day, close_value) data_list = [] temp_list = [] for day, line in enumerate(reversed(data_lines[1:301])): #print(line) # test close_value = float(line[4]) data_list.append((day+1, close_value)) temp_list.append(close_value) max_val = max(temp_list) + 3 min_val = min(temp_list) - 3 print(len(data_lines), start_date, end_date, max_val, min_val) # test app = wx.App(0) caption = "Line graph of stock values" frame = MyFrame(data_list, start_date, end_date, ticker, max_val, min_val) frame.Center() frame.Show() app.MainLoop()
May 'the Google' be with you!
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)
# use wxPython's wx.html.HtmlWindow to create colorful text # tested with Python25 and wxPython28 by vegaseat import wx import wx.html def do_html(text, color='black', size=3): """create a line of html code for text with color and size""" sf = "<FONT color=%s size=%d>%s</FONT>" return sf % (color, size, text) # build up simple HTML code ... # text between <B> and </B> is bold # <BR> inserts a line break (new line) html = "" html += do_html("Create colorful text ", "red") html += do_html("with html code to be", "blue") html += '<BR>' html += do_html("displayed in wxPython's ", "green") html += do_html("wx.html.HtmlWindow", "brown") html += '<BR><BR>' orange = "#FFBA00" # gives a better orange color color_list = ['red', orange, 'yellow', 'green', 'blue'] ix = 0 for c in 'WE LOVE RAINBOWS': # make character c bold c = "<B>" + c + "</B>" if ix >= len(color_list): ix = 0 html += do_html(c, color_list[ix], 7) ix += 1 # set up the GUI window/frame ... app = wx.App(0) mytitle = "wx.html.HtmlWindow for colorful text" width = 420 height = 160 # make parent None frame = wx.Frame(None, id=-1, size=(width, height), title=mytitle) # create an html label/window htmlwin = wx.html.HtmlWindow(parent=frame, id=-1) # display the html code htmlwin.SetPage(html) frame.Show(True) frame.Center() app.MainLoop()
May 'the Google' be with you!
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 ...
python Syntax (Toggle Plain Text)
# explore wxPython # wx.Timer() one_shot and wx.StopWatch() example # a one_shot delays for a set time # tested with Python25 and wxPython28 by vegaseat import wx class MyFrame(wx.Frame): def __init__(self, parent, mytitle, mysize): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize) self.SetBackgroundColour('red') self.watch = wx.StopWatch() self.timer = wx.Timer(self) # interval = 2000ms (2 seconds) # default is oneShot=False, timer keeps restarting self.timer.Start(2000, oneShot=True) self.watch.Start() self.SetTitle("stopwatch started") # bind EVT_TIMER event to self.onTimer() action self.Bind(wx.EVT_TIMER, self.onTimer) def onTimer(self, event): # establish new color self.SetBackgroundColour('green') # clear old color, set to new color self.ClearBackground() # pause/stop the stopwatch and get its time self.watch.Pause() time = self.watch.Time() s = "stopwatch stopped at %s milliseconds" % time self.SetTitle(s) app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, '---', (500, 100)).Show() app.MainLoop()
May 'the Google' be with you!
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:
Notice the special requirement for Linux users.
python Syntax (Toggle Plain Text)
# testing wxPython's # wx.TextCtrl(parent, id, value, pos, size, style) # a widget used for text data input or output # note: # style=wx.TE_PROCESS_ENTER is needed for Linux to # respond to the enter key event!!! # snee import wx class MyFrame(wx.Frame): def __init__(self, parent, mytitle, mysize): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize) self.SetBackgroundColour("yellow") s = "Enter name below:" edit_label = wx.StaticText(self, wx.ID_ANY, s) # create a single line edit input area self.edit = wx.TextCtrl(self, wx.ID_ANY, value="", style=wx.TE_PROCESS_ENTER) # put the cursor in edit self.edit.SetFocus() # respond to enter key when focus is on edit self.edit.Bind(wx.EVT_TEXT_ENTER, self.onEnter) # create a scrolled multiline text output area self.text_out = wx.TextCtrl(self, wx.ID_ANY, value="", style=wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY) # use a box sizer for vertical widget layout sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(edit_label, 0, wx.LEFT|wx.TOP|wx.EXPAND, border=10) sizer.Add(self.edit, 0, wx.ALL|wx.EXPAND, border=10) sizer.Add(self.text_out, 2, wx.ALL|wx.EXPAND, border=10) self.SetSizer(sizer) def onEnter(self, event): """the Enter key has been pressed, do something""" # GetValue() gives a string name = self.edit.GetValue() s = "You entered the name: " + name + '\n' # text output, either method works #self.text_out.AppendText(s) self.text_out.WriteText(s) # clear edit input space self.edit.Clear() app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'testing wx.TextCtrl()', (300, 480)).Show() app.MainLoop()
Last edited by sneekula; 15 Days Ago at 3:31 pm.
No one died when Clinton lied.
![]() |
Similar Threads
- Starting Python (Python)
- Autoupdater in wxPython (Python)
- what is python (Python)
Other Threads in the Python Forum
- Previous Thread: sudoku solver problem
- Next Thread: Password Generator
| Thread Tools | Search this Thread |
accessdenied advanced apache application approximation argv array beginner book builtin calculator change command converter countpasswordentry csv curved dan08 def dictionary dynamic edit enter event file float format function google homework import inches input jaunty keyboard lapse library line lines linux list lists loop microphone mouse movingimageswithpygame mysqlquery newb number numbers numeric obexftp output parameters parsing path phonebook plugin prime programming py2exe pygame pyopengl python random recursion redirect remote return reverse scrolledtext session simple skinning software sprite statictext string strings syntax table terminal text textarea threading time tlapse trick tuple tutorial twoup ubuntu unicode unit urllib urllib2 variable voip wordgame wxpython






