# 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()
# 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()
# 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()
# 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()
# 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()
# 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()
# create a simple image slide show using the # wx.PaintDC surface as a canvas and # DrawBitmap(bitmap, x, y, bool transparent) # vegaseat import wx import os class ShowPic(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, wx.ID_ANY, 'MyFrame', size=(773,632)) self.panel = wx.Panel(self) # seconds per slide self.delay = 2 # number of loops per slide show self.loops = 2 # list of image files you have in the working directory self.images = ["Pic1.png", "Pic2.png", "Pic3.png"] # create a list of bitmap image objects self.image_list = [] for image_file in self.images: if os.path.exists(image_file): print(image_file) # test self.image_list.append(wx.Bitmap(image_file)) else: self.SetTitle("No pictures found!") # bind the panel to the paint event wx.EVT_PAINT(self.panel, self.onPaint) def onPaint(self, event=None): # this is the wxPython drawing surface/canvas dc = wx.PaintDC(self.panel) while self.loops: self.loops -= 1 for ix, bmp in enumerate(self.image_list): # clear the canvas dc.Clear() # optionally show image name self.SetTitle(self.images[ix]) # draw the image dc.DrawBitmap(bmp, 10, 10, True) # wait self.delay seconds to show next slide wx.Sleep(self.delay) if __name__=='__main__': app = wx.App(0) frame = ShowPic(parent=None) frame.Show() app.MainLoop()
# use a drawing bitmap and wx.MemoryDC to create a canvas you can # draw on and optionally save the drawing to an image file # vegaseat import wx class MyFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(400, 150)) # create a bitmp for display and optional saving self.show_bmp = wx.StaticBitmap(self) # get the width and height for the blank bitmap w, h = self.GetClientSize() # create a blank bitmap as a drawing background draw_bmp = wx.EmptyBitmap(w, h) # put the canvas on top of draw_bmp canvas = wx.MemoryDC(draw_bmp) # fill the canvas white canvas.SetBrush(wx.Brush('white')) canvas.Clear() # now draw something on the canvas ... # set line colour and thickness (pixels) canvas.SetPen(wx.Pen("blue", 15)) # DrawLine(x1, y1, x2, y2) from point (x1,y1) to (x2,y2) canvas.DrawLine(50, 60, 340, 60) # this also shows your drawing self.show_bmp.SetBitmap(draw_bmp) # optioally save the created image # get the image object myimage = self.show_bmp.GetBitmap() myimage.SaveFile("myimage.jpg", wx.BITMAP_TYPE_JPEG) app = wx.App(0) MyFrame(None, 'draw a line using wx.MemoryDC').Show(True) app.MainLoop()
# use a drawing bitmap and wx.MemoryDC to create a canvas you can # draw on and optionally save the drawing to an image file # here we draw two images side by side and save the combined image # vegaseat code modified by sneek import wx class MyFrame(wx.Frame): def __init__(self, parent, title, mysize): wx.Frame.__init__(self, parent, -1, title, size=mysize) # create a bitmp for display and optional saving self.show_bmp = wx.StaticBitmap(self) # get the width and height for the blank bitmap w, h = self.GetClientSize() # create a blank bitmap as a drawing background # should be large enough to fit the 2 images side by side draw_bmp = wx.EmptyBitmap(w, h) # put a canvas on top of draw_bmp canvas = wx.MemoryDC(draw_bmp) # fill the canvas white canvas.SetBrush(wx.Brush('white')) canvas.Clear() # pick 2 image files you have in the working folder # (can be a .jpg, .png, .gif, .bmp image files) # note that filenames are case sensitive in Linux image1 = wx.Bitmap("Duck_right.jpg") image2 = wx.Bitmap("Duck_left.jpg") # draw the 2 images side by side canvas.DrawBitmap(image1, 0, 0) canvas.DrawBitmap(image2, w/2, 0) # this also shows your drawing self.show_bmp.SetBitmap(draw_bmp) # get the image object myimage = self.show_bmp.GetBitmap() # save it to a file myimage.SaveFile("joined_pic1.jpg", wx.BITMAP_TYPE_JPEG) app = wx.App(0) # make width w large enough to have the 2 images next to each other w = 610 # make height h large enough to fit the max height of the 2 images h = 210 mysize = (w, h) MyFrame(None, 'join two images and save', mysize).Show(True) app.MainLoop()
| DaniWeb Message | |
| Cancel Changes | |