| | |
Starting wxPython (GUI code)
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
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:
python Syntax (Toggle Plain Text)
# experiments with wxPython, reference across class instances # from one panel class to another panel class import wx import time class MakePanel1(wx.Panel): def __init__(self, Parent, *args, **kwargs): wx.Panel.__init__(self, Parent, *args, **kwargs) self.SetBackgroundColour('yellow') self.label = wx.StaticText(self, -1, " panel1 label ") self.hbox = wx.BoxSizer(wx.HORIZONTAL) self.hbox.Add(self.label, 0, wx.ALL, 20) self.SetSizer(self.hbox) class MakePanel2(wx.Panel): def __init__(self, Parent, *args, **kwargs): wx.Panel.__init__(self, Parent, *args, **kwargs) self.SetBackgroundColour('green') self.button = wx.Button(self, label=" panel2 button ") self.button.Bind(wx.EVT_BUTTON, self.buttonClick ) self.hbox = wx.BoxSizer(wx.HORIZONTAL) self.hbox.Add(self.button, 0, wx.ALL, 20) self.SetSizer(self.hbox) def buttonClick(self, event=None): # reference panel1's label via frame.panel1 s1 = "panel1 label ..... \n" s2 = "the time is " + time.strftime("%H:%M:%S", time.localtime()) frame.panel1.label.SetLabel(s1 + s2) class MakeFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.panel1 = MakePanel1(self) self.panel2 = MakePanel2(self) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(self.panel1,1,wx.EXPAND); vbox.Add(self.panel2,1,wx.EXPAND); self.SetSizer(vbox) # select a frame size so everything fits self.Fit() app = wx.App(0) # instance frame is needed for later reference frame = MakeFrame(None) frame.Show(True) app.MainLoop()
drink her pretty
If you like to draw things, here is an example how to draw some basic shapes on wxPython's canvas:
python Syntax (Toggle Plain Text)
# draw a few well known shapes on a wx.PaintDC() canvas import wx class MyFrame(wx.Frame): def __init__(self, parent=None, title=None): wx.Frame.__init__(self, parent, wx.ID_ANY, title) self.panel = wx.Panel(self, size=(350, 450)) # this sets up the painting canvas self.panel.Bind(wx.EVT_PAINT, self.on_paint) # set frame size to fit panel self.Fit() def on_paint(self, event): # establish the painting canvas dc = wx.PaintDC(self.panel) # draw some lines using the given pen specs # from points (x1, y1) to (x2, y2) x1 = 50 y1 = 20 x2 = 300 y2 = 20 # first pen colour is red (thickness = 5) dc.SetPen(wx.Pen('red', 5)) dc.DrawLine(x1, y1, x2, y2) # second pen colour is white dc.SetPen(wx.Pen('white', 5)) dc.DrawLine(x1, y1+5, x2, y2+5) # third pen colour is blue dc.SetPen(wx.Pen('blue', 5)) dc.DrawLine(x1, y1+10, x2, y2+10) # draw a red rounded-rectangle # upper left corner coordinates x, y and width, height # make the pen colour red (thickness = 1) # default brush (fill) is white dc.SetPen(wx.Pen('red', 1)) x = 50 y = 50 w = 100 h = 100 rect = wx.Rect(x, y, w, h) # corners are quarter-circles using a radius of 8 dc.DrawRoundedRectangleRect(rect, 8) # draw a red circle with yellow fill # center coordinates x, y and radius r dc.SetBrush(wx.Brush('yellow')) x = 250 y = 100 r = 50 dc.DrawCircle(x, y, r) # draw an arc from point x1, y1 to point x2, y2 counter # clockwise along a circle with center xc, yc # use previous pen and brush settings xc = 100 yc = 220 x1 = xc y1 = 170 x2 = xc y2 = 270 dc.DrawArc(x1, y1, x2, y2, xc, yc) # draw a polygon connecting the (x, y) points in a list # will also connect first and last points point_list = [(10, 10), (120, 20), (100, 80), (50, 100)] dc.DrawPolygon(point_list, xoffset=180, yoffset=170) # draw 2 gradient filled rectangles # upper left corner coordinates x, y and width, height x = 50 y = 300 w = 100 h = 100 dc.DrawRectangle(x, y, w, h) dc.GradientFillLinear((x, y, w, h), 'red', 'blue') # just a little different fill dc.DrawRectangle(x+150, y, w, h) dc.GradientFillConcentric((x+150, y, w, h), 'red', 'blue', (50, 50)) # test it ... app = wx.App(0) MyFrame(title='put some shapes on a canvas').Show() app.MainLoop()
Last edited by Ene Uran; Aug 4th, 2008 at 4:57 pm. Reason: added corner radius comment
drink her pretty
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):
python Syntax (Toggle Plain Text)
# load, sort and clear a wxPython # wx.ListBox(parent, id, pos, size, choices, style) import wx class MyFrame(wx.Frame): def __init__(self, parent, mytitle, name_list): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle) self.SetBackgroundColour("green") self.name_list = list(name_list) self.listbox = wx.ListBox(self, wx.ID_ANY, choices=[]) self.listbox.Bind(wx.EVT_LISTBOX, self.listboxClick) # create action widgets self.load_button = wx.Button(self, wx.ID_ANY, "load ListBox") self.clear_button = wx.Button(self, wx.ID_ANY, "clear ListBox") self.sort_button = wx.Button(self, wx.ID_ANY, "sort ListBox") # bind mouse event to an action self.load_button.Bind(wx.EVT_BUTTON, self.load_buttonClick) self.clear_button.Bind(wx.EVT_BUTTON, self.clear_buttonClick) self.sort_button.Bind(wx.EVT_BUTTON, self.sort_buttonClick) # create an output widget self.label = wx.StaticText(self, wx.ID_ANY, "") sizer = wx.GridBagSizer(vgap=5, hgap=5) # pos=(row, column) span=(rowspan, columnspan) # wx.ALL puts the specified border on all sides sizer.Add(self.load_button, pos=(0, 0), flag=wx.ALL, border=5) # listbox spans 6 rows and 2 columns sizer.Add(self.listbox, pos=(1, 0), span=(6, 2), flag=wx.ALL|wx.EXPAND, border=5) sizer.Add(self.clear_button, pos=(7, 1), flag=wx.ALL, border=5) sizer.Add(self.sort_button, pos=(7, 0), flag=wx.ALL, border=5) sizer.Add(self.label, pos=(8, 0), flag=wx.ALL, border=5) self.SetSizer(sizer) # size the frame so all the widgets fit self.Fit() def load_buttonClick(self, event): """load the name list into the bistbox""" # use self.listbox.Set(name_list) or ... for name in self.name_list: self.listbox.Append(name) def clear_buttonClick(self, event): """clear all items from the listbox""" self.listbox.Clear() self.label.SetLabel("") def sort_buttonClick(self, event): """sort the items in the listbox""" # GetItems() is new in wxPython2.8 # puts the listbox items into a list name_list = self.listbox.GetItems() name_list.sort() # Set() clears and reloads the listbox self.listbox.Set(name_list) def listboxClick(self, event): """display the selected ListBox item""" selected_item = self.listbox.GetStringSelection() s = "You selected " + selected_item self.label.SetLabel(s) name_list = [ "Andreas", "Erich", "Udo", "Jens", "Bjorn", "Heidrun", "Klaus", "Ulla", "Volger", "Helmut", "Freja", "Larry", "Harry" ] app = wx.App(0) # create the MyFrame instance and then show the frame MyFrame(None, 'listbox test', name_list).Show() app.MainLoop()
Last edited by sneekula; Aug 4th, 2008 at 10:46 pm. Reason: darn spelling
No one died when Clinton lied.
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 ...
python Syntax (Toggle Plain Text)
# wxPython's amazing wx.gizmos.EditableListBox() # you can edit (also cut, copy, paste), delete, move selected # items up or down, and insert (also paste) a new item # tested with Python25 and wxPython28 vegaseat 07aug2008 import wx import wx.gizmos class MyFrame(wx.Frame): def __init__(self, parent, mytitle, name_list): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle) self.panel = wx.Panel(self, wx.ID_ANY) self.panel.SetBackgroundColour("green") self.name_list = list(name_list) self.elistbox = wx.gizmos.EditableListBox(self.panel, wx.ID_ANY, label="List of Names") # get the actual control portion of the EditableListBox self.actual_listctrl = self.elistbox.GetListCtrl() # binds to any newly focused/selected item self.actual_listctrl.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.listctrlClick) # create action widgets load_button = wx.Button(self.panel, wx.ID_ANY, "load ListBox") clear_button = wx.Button(self.panel, wx.ID_ANY, "clear ListBox") sort_button = wx.Button(self.panel, wx.ID_ANY, "sort ListBox") # bind mouse click event to an action load_button.Bind(wx.EVT_BUTTON, self.load_buttonClick) clear_button.Bind(wx.EVT_BUTTON, self.clear_buttonClick) sort_button.Bind(wx.EVT_BUTTON, self.sort_buttonClick) # create an output widget self.label = wx.StaticText(self.panel, wx.ID_ANY, "") sizer = wx.GridBagSizer(vgap=5, hgap=5) # pos=(row, column) span=(rowspan, columnspan) # wx.ALL puts the specified border on all sides sizer.Add(load_button, pos=(0, 0), flag=wx.ALL, border=5) # listbox spans 6 rows and 2 columns sizer.Add(self.elistbox, pos=(1, 0), span=(6, 2), flag=wx.ALL|wx.EXPAND, border=5) sizer.Add(clear_button, pos=(7, 1), flag=wx.ALL, border=5) sizer.Add(sort_button, pos=(7, 0), flag=wx.ALL, border=5) sizer.Add(self.label, pos=(8, 0), flag=wx.ALL, border=5) # set the sizer and fit all its widgets self.panel.SetSizerAndFit(sizer) # size the frame so all its widgets fit inside self.Fit() def load_buttonClick(self, event): """load the name list into the bistbox""" self.elistbox.SetStrings(name_list) def clear_buttonClick(self, event): """clear all items from the elistbox""" self.elistbox.SetStrings([]) self.label.SetLabel("") def sort_buttonClick(self, event): """sort the items in the elistbox""" # GetStrings() puts the elistbox items into a list name_list = self.elistbox.GetStrings() name_list.sort() # SetStrings() clears and reloads the elistbox self.elistbox.SetStrings(name_list) def listctrlClick(self, event): """display the selected listctrl item of the elistbox""" for n in range(self.actual_listctrl.GetItemCount()): state = wx.LIST_STATE_SELECTED if self.actual_listctrl.GetItemState(n, state): selected_item = self.actual_listctrl.GetItemText(n) s = "You selected " + selected_item self.label.SetLabel(s) name_list = [ "Erich", "Udo", "Jens", "Bjorn", "Heidrun", "Klaus", "Zoe", "Ulla", "Volger", "Helmut", "Lisa", "Larry", "Andreas", "Harry" ] app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'elistbox test', name_list).Show() app.MainLoop()
Last edited by vegaseat; Aug 7th, 2008 at 12:08 pm. Reason: or
May 'the Google' be with you!
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 ...
python Syntax (Toggle Plain Text)
# the Open Graphics Library (OGL) is now part of wxPython # also test use of a custom class derived from ogl.PolygonShape # tested with Python25 and wxPython28 vegaseat 08aug2008 import wx import wx.lib.ogl as ogl class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__( self, None, wx.ID_ANY, "wx.lib.ogl Demo2", size=(400,300)) canvas = ogl.ShapeCanvas(self) canvas.SetBackgroundColour("yellow") diagram = ogl.Diagram() # marry the two ... canvas.SetDiagram(diagram) diagram.SetCanvas(canvas) # draw some standard shapes ... # (check how creation order affects overlap) circle = ogl.CircleShape(80.0) # radius circle.SetX(125.0) # center x circle.SetY(125.0) # use preset pen and brush types # border ... circle.SetPen(wx.RED_PEN) # fill ... circle.SetBrush(wx.GREEN_BRUSH) canvas.AddShape(circle) rectangle = ogl.RectangleShape(100, 80) # (w, h) rectangle.SetX(55.0) # center x rectangle.SetY(45.0) # center y # use wx.Pen and wx.Brush for more options # wx.Pen(colour, width=1, style=wx.SOLID) # also wx.DOT, wx.DOT_DASH, wx.TRANSPARENT --> no border rectangle.SetPen(wx.Pen("blue", 2)) # wxBrush(colour, style=wx.SOLID) # also wx.CROSS_HATCH, wx.CROSSDIAG_HATCH, wx.TRANSPARENT rectangle.SetBrush(wx.Brush("blue", wx.CROSSDIAG_HATCH)) canvas.AddShape(rectangle) text = ogl.TextShape(250, 30) # (w, h) text.SetX(180) # center x text.SetY(240) text.AddText("you can drag the shapes or the text") canvas.AddShape(text) # if you have an image file # you can also create a shape with the image image_file = 'victory.jpg' bmp = wx.Bitmap(image_file) picture = ogl.BitmapShape() picture.SetBitmap(bmp) picture.SetX(330) # center x picture.SetY(160) canvas.AddShape(picture) # use the custom class ... circle = DiamondShape(130, 100) # (w, h) circle.SetX(225.0) # center x circle.SetY(70.0) circle.SetPen(wx.BLACK_PEN) # use no fill ... circle.SetBrush(wx.TRANSPARENT_BRUSH) canvas.AddShape(circle) # all the shapes are in, so show them diagram.ShowAll(True) # use a sizer sizer = wx.BoxSizer(wx.VERTICAL) # canvas will grow as frame is stretched sizer.Add(canvas, 1, wx.GROW) self.SetSizer(sizer) class DiamondShape(ogl.PolygonShape): """create a diamond shaped object using a polygon""" def __init__(self, w=60.0, h=60.0): ogl.PolygonShape.__init__(self) points = [(0, -h/2.0), (w/2.0, 0), (0,h/2.0), (-w/2.0, 0)] self.Create(points) app = wx.App(0) ogl.OGLInitialize() MyFrame().Show() app.MainLoop()
Last edited by vegaseat; Aug 8th, 2008 at 4:23 pm. Reason: notes
May 'the Google' be with you!
To allow just one instance of your wxPython program to run, you need to modify your application class slightly ...
python Syntax (Toggle Plain Text)
# allow only one instance of a wxPython program to run import wx class MyFrame(wx.Frame): def __init__(self,parent, mytitle): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=(300, 90)) self.SetBackgroundColour("red") self.Centre() # more of your program code here ... class SingleApp(wx.App): def OnInit(self): name = "SingleApp-%s" % (wx.GetUserId()) self.instance = wx.SingleInstanceChecker(name) # create a title mytitle = name if self.instance.IsAnotherRunning(): message = "Another instance of %s is running" % mytitle wx.MessageBox(message, "Error") return False MyFrame(None, mytitle).Show() return True app = SingleApp() app.MainLoop()
May 'the Google' be with you!
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 ...
python Syntax (Toggle Plain Text)
# test the wx.RadioBox() widget # wx.RadioBox(parent, id, label, pos, size, choices, majorDimension, style) # combines a wx.StaticBox() with a wx.RadioButton() # only one radiobutton can be selected at a time in the radiobox import wx class MyFrame(wx.Frame): def __init__(self, parent, mytitle): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle) self.SetBackgroundColour("yellow") # create input widgets self.options1 = ['now', 'later', 'much later', 'never'] self.radiobox1 = wx.RadioBox(self, wx.ID_ANY, " Select one option ", choices=self.options1, style=wx.VERTICAL) # set radio button 1 as selected (first button is 0) self.radiobox1.SetSelection(1) # bind mouse click to an action self.radiobox1.Bind(wx.EVT_RADIOBOX, self.onAction) self.options2 = ['blue', 'red', 'yellow', 'orange', 'green', 'purple', 'navy blue', 'black', 'gray'] # this radio box has 3 columns self.radiobox2 = wx.RadioBox(self, wx.ID_ANY, label=" What color would you like? ", choices=self.options2, majorDimension=3, style=wx.RA_SPECIFY_COLS) self.radiobox2.SetSelection(0) self.radiobox2.Bind(wx.EVT_RADIOBOX, self.onAction) # create output widgets self.label1 = wx.StaticText(self, wx.ID_ANY, "" ) self.label2 = wx.StaticText(self, wx.ID_ANY, "" ) # use box sizers to layout widgets # the two vertical sizers nest in the horizontal sizer sizer_v1 = wx.BoxSizer(wx.VERTICAL) sizer_v2 = wx.BoxSizer(wx.VERTICAL) sizer_h = wx.BoxSizer(wx.HORIZONTAL) # add the widgets to the corresponding vertical sizer sizer_v1.Add(self.radiobox1, 0, flag=wx.ALL, border=10) sizer_v1.Add(self.label1, 0, wx.ALL, 10) sizer_v2.Add(self.radiobox2, 0, wx.ALL, 10) # add a spacer (optional) ... sizer_v2.Add((0, 0), 0, wx.ALL, 10) sizer_v2.Add(self.label2, 0, wx.ALL, 10) # put the 2 vertical sizers into the horizontal sizer sizer_h.Add(sizer_v1, 0) sizer_h.Add(sizer_v2, 0) # it's the horizontal sizer you have to set # also fit the frame snuggly around the whole thing self.SetSizerAndFit(sizer_h) # show present selection self.onAction(None) def onAction(self, event): """show the selected choice""" index1 = self.radiobox1.GetSelection() s = "Choice = " + self.options1[index1] self.label1.SetLabel(s) # dito for radio box #2 index2 = self.radiobox2.GetSelection() s = "Choice = " + self.options2[index2] self.label2.SetLabel(s) app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'testing wx.RadioBox()').Show() app.MainLoop()
May 'the Google' be with you!
You can also create a radio-button like behaviour in a menu using radio-items. Take a look at this menu example ...
python Syntax (Toggle Plain Text)
# experimenting with wxPython's wx.Menu() import wx # some needed unique ids for the radio item menu ID_RED = 1001 ID_GREEN = 1002 ID_BLUE = 1003 ID_YELLOW = 1004 ID_WHITE = 1005 class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'Click on a menubar item', size=(300, 350)) # create a status bar at the bottom self.CreateStatusBar() self.SetStatusText("This is the statusbar") self.createMenu() def createMenu(self): """creates all the menu items""" filemenu = wx.Menu() filemenu_save = filemenu.Append(wx.ID_ANY, "&Save", "Save something to file (just a dummy)") filemenu.AppendSeparator() filemenu_exit = filemenu.Append(wx.ID_ANY, "E&xit", "Quit the program") optionmenu = wx.Menu() self.optionmenu = optionmenu optionmenu.AppendRadioItem(ID_RED, "red", "") optionmenu.AppendRadioItem(ID_GREEN, "green", "") optionmenu.AppendRadioItem(ID_BLUE, "blue", "") optionmenu.AppendRadioItem(ID_YELLOW, "yellow", "") optionmenu.AppendRadioItem(ID_WHITE, "white", "") helpmenu = wx.Menu() # the optional & allows you to use alt/a # the last string argument shows in the status bar # on mouse_over helpmenu_about = helpmenu.Append(wx.ID_ANY, "&About", "About message") # create a menu bar at the top for the menu titles menuBar = wx.MenuBar() menuBar.Append(filemenu, "&File") menuBar.Append(optionmenu, "&Option") menuBar.Append(helpmenu, "&Help") self.SetMenuBar(menuBar) # bind the menu events to an action method self.Bind(wx.EVT_MENU, self.onMenuAbout, helpmenu_about) self.Bind(wx.EVT_MENU, self.onMenuSave, filemenu_save) self.Bind(wx.EVT_MENU, self.onMenuExit, filemenu_exit) """ self.Bind(wx.EVT_MENU, self.onMenuColor, id=ID_RED) self.Bind(wx.EVT_MENU, self.onMenuColor, id=ID_GREEN) self.Bind(wx.EVT_MENU, self.onMenuColor, id=ID_BLUE) self.Bind(wx.EVT_MENU, self.onMenuColor, id=ID_YELLOW) self.Bind(wx.EVT_MENU, self.onMenuColor, id=ID_WHITE) """ # better give id range ... self.Bind(wx.EVT_MENU_RANGE, self.onMenuColor, id=ID_RED, id2=ID_WHITE) # set the preselected colour self.onMenuColor(self) def onMenuAbout(self, event): dlg = wx.MessageDialog(self, "a simple application using wxFrame, wxMenu\n" "a statusbar, and this about message.", "About", wx.OK|wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() def onMenuSave(self, event): self.SetStatusText("Not implemented yet!") def onMenuColor(self, event): for item in self.optionmenu.GetMenuItems(): #print item, item.IsChecked(), item.GetLabel() # test if item.IsChecked(): # establish new color self.SetBackgroundColour(item.GetLabel()) # now clear old color and set to new color self.ClearBackground() def onMenuExit(self, event): # exit via wx.EVT_CLOSE event self.Close(True) app = wx.App(0) # create class instance MyFrame().Show() # start the event loop app.MainLoop()
May 'the Google' be with you!
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:
python Syntax (Toggle Plain Text)
# a practical use of wxPython's wx.grid.Grid() widget # load the grid via a list of lists # bind cell select (mouse left click) import wx import wx.grid class MyGrid(wx.grid.Grid): def __init__(self, parent, data_list): wx.grid.Grid.__init__(self, parent, wx.ID_ANY) self.parent = parent # set the rows and columns the grid needs self.rows = len(data_list) self.cols = len(data_list[0]) self.CreateGrid(self.rows, self.cols) # set some column widths (default is 80) different self.SetColSize(0, 180) self.SetColSize(3, 100) self.SetRowLabelSize(40) # sets leading row width # set column lable titles at the top for ix, title in enumerate(data_list[0]): self.SetColLabelValue(ix, title) # create reusable attribute objects self.attr = wx.grid.GridCellAttr() self.attr.SetTextColour('black') self.attr.SetBackgroundColour('yellow') #self.attr.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)) # select the cell with a mouse left click self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.onCellLeftClick) self.loadCells(data_list) def onCellLeftClick(self, event): row = event.GetRow() col = event.GetCol() self.parent.SetTitle("row=%d col=%d value=%s" % (row, col, self.GetCellValue(row, col))) # move the grid's cursor to frame the cell self.SetGridCursor(row, col) def loadCells(self, data_list): # note that title row is taken for row in range(1, self.rows): # set cell attributes for the whole row self.SetRowAttr(row-1, self.attr) for col in range(self.cols): value = data_list[row][col] self.SetCellValue(row-1, col, value) self.SetReadOnly(row-1, col, True) if col > 0: self.SetCellAlignment(row-1, col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE) self.SetCellTextColour(row, 0, 'red') self.SetCellBackgroundColour(row, 0, 'white') self.SetCellFont(row, 0, wx.Font(8, wx.ROMAN, wx.ITALIC, wx.NORMAL)) honor = "University of Detroit Chemistry Department" self.SetCellValue(row, 0, honor) # build the data_list, raw_data string is from a csv file ... raw_data = """\ Solvent Name, BP (deg C), MP (deg C), Density (g/ml) ACETIC ACID,117.9,16.7,1.049 ACETIC ANHYDRIDE,140.1,-73.1,1.087 ACETONE,56.3,-94.7,0.791 ACETONITRILE,81.6,-43.8,0.786 ANISOLE,154.2,-37,0.995 BENZYL ALCOHOL,205.4,-15.3,1.045 BENZYL BENZOATE,323.5,19.4,1.112 BUTYL ALCOHOL NORMAL,117.7,-88.6,0.81 BUTYL ALCOHOL SEC,99.6,-114.7,0.805 BUTYL ALCOHOL TERTIARY,82.2,25.5,0.786 CHLOROBENZENE,131.7,-45.6,1.111 CYCLOHEXANE,80.7,6.6,0.779 CYCLOHEXANOL,161.1,25.1,0.971 CYCLOHEXANONE,155.2,-47,0.947 DICHLOROETHANE 1 2,83.5,-35.7,1.246 DICHLOROMETHANE,39.8,-95.1,1.325 DIETHYL ETHER,34.5,-116.2,0.715 DIMETHYLACETAMIDE,166.1,-20,0.937 DIMETHYLFORMAMIDE,153.3,-60.4,0.944 DIMETHYLSULFOXIDE,189.4,18.5,1.102 DIOXANE 1 4,101.3,11.8,1.034 DIPHENYL ETHER,258.3,26.9,1.066 ETHYL ACETATE,77.1,-83.9,0.902 ETHYL ALCOHOL,78.3,-114.1,0.789 ETHYL DIGLYME,188.2,-45,0.906 ETHYLENE CARBONATE,248.3,36.4,1.321 ETHYLENE GLYCOL,197.3,-13.2,1.114 FORMIC ACID,100.6,8.3,1.22 HEPTANE,98.4,-90.6,0.684 HEXAMETHYL PHOSPHORAMIDE,233.2,7.2,1.027 HEXANE,68.7,-95.3,0.659 ISO OCTANE,99.2,-107.4,0.692 ISOPROPYL ACETATE,88.6,-73.4,0.872 ISOPROPYL ALCOHOL,82.3,-88,0.785 METHYL ALCOHOL,64.7,-97.7,0.791 METHYL ETHYLKETONE,79.6,-86.7,0.805 METHYL ISOBUTYL KETONE,116.5,-84,0.798 METHYL T-BUTYL ETHER,55.5,-10,0.74 METHYLPYRROLIDINONE N,203.2,-23.5,1.027 MORPHOLINE,128.9,-3.1,1 NITROBENZENE,210.8,5.7,1.208 NITROMETHANE,101.2,-28.5,1.131 PENTANE,36.1, -129.7,0.626 PHENOL,181.8,40.9,1.066 PROPANENITRILE,97.1,-92.8,0.782 PROPIONIC ACID,141.1,-20.7,0.993 PROPIONITRILE,97.4,-92.8,0.782 PROPYLENE GLYCOL,187.6,-60.1,1.04 PYRIDINE,115.4,-41.6,0.978 SULFOLANE,287.3,28.5,1.262 TETRAHYDROFURAN,66.2,-108.5,0.887 TOLUENE,110.6,-94.9,0.867 TRIETHYL PHOSPHATE,215.4,-56.4,1.072 TRIETHYLAMINE,89.5,-114.7,0.726 TRIFLUOROACETIC ACID,71.8,-15.3,1.489 WATER,100,0,1 XYLENES,139.1,-47.8,0.86""" data_list = [] for line in raw_data.split('\n'): line_list = line.split(',') data_list.append(line_list) app = wx.App(0) # create a window/frame, no parent, use a default ID title = "test the wx.grid.Grid()" frame = wx.Frame(None, wx.ID_ANY, title, size=(520, 360)) # create the class instance mygrid = MyGrid(frame, data_list) frame.Show(True) app.MainLoop()
No one died when Clinton lied.
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 ...
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 ...
python Syntax (Toggle Plain Text)
# experiments with wxPython's wx.Notebook() widget # converting distance, area and volume units # tested with Python25 and wxPython28 by vegaseat 11aug2008 import wx class MyNotebook(wx.Frame): def __init__(self, parent, title, distD, areaD, volD): wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(460, 360)) # style=wx.NB_TOP is default # could use style=wx.NB_BOTTOM nb = wx.Notebook(self, wx.ID_ANY) # MyPage(parent, conversion dictionary, preselected choice) self.page1 = MyPage(nb, distD, 3) self.page2 = MyPage(nb, areaD, 2) self.page3 = MyPage(nb, volD, 0) nb.AddPage(self.page1, "Distance Conversion") nb.AddPage(self.page2, "Area Conversion") nb.AddPage(self.page3, "Volume Conversion") # start with page1 active self.page1.SetFocus() class MyPage(wx.Panel): """ each panel instance creates the notbook page content from the given conversion dictionary convD """ def __init__(self, parent, convD, preselect): wx.Panel.__init__(self, parent, wx.ID_ANY) oatmeal3 = '#FCFFE1' self.SetBackgroundColour(oatmeal3) self.convD = convD # create list of possible units self.options = convD.keys() self.radiobox1 = wx.RadioBox(self, wx.ID_ANY, "Select a unit to convert from", choices=self.options, style=wx.VERTICAL) # set radio button 1 as selected (first button is 0) self.radiobox1.SetSelection(preselect) # bind mouse click to an action self.radiobox1.Bind(wx.EVT_RADIOBOX, self.onAction) self.radiobox2 = wx.RadioBox(self, wx.ID_ANY, "Select a unit to convert to ", choices=self.options, style=wx.VERTICAL) # set radio button 1 as selected (first button is 0) self.radiobox2.SetSelection(preselect) # bind mouse click to an action self.radiobox2.Bind(wx.EVT_RADIOBOX, self.onAction) # additional widgets self.label1 = wx.StaticText(self, wx.ID_ANY, "" ) self.label2 = wx.StaticText(self, wx.ID_ANY, "" ) self.edit1 = wx.TextCtrl(self, wx.ID_ANY, value="1.0", size=(150, 20)) # respond to enter key when focus is on edit1 self.edit1.Bind(wx.EVT_TEXT_ENTER, self.onAction) self.edit2 = wx.TextCtrl(self, wx.ID_ANY, value="", size=(150, 20)) self.button = wx.Button(self, wx.ID_ANY, label='Convert') self.button.Bind(wx.EVT_BUTTON, self.onAction) # use box sizers to layout the widgets # nest the 3 vertical sizers in the horizontal sizer later sizer_v1 = wx.BoxSizer(wx.VERTICAL) sizer_v2 = wx.BoxSizer(wx.VERTICAL) sizer_v3 = wx.BoxSizer(wx.VERTICAL) sizer_h = wx.BoxSizer(wx.HORIZONTAL) # add the widgets to the corresponding vertical sizer sizer_v1.Add(self.radiobox1, 0, flag=wx.ALL, border=10) sizer_v1.Add(self.label1, 0, wx.LEFT|wx.RIGHT|wx.TOP, 10) sizer_v1.Add(self.edit1, 0, wx.LEFT|wx.RIGHT, 10) # add a spacer to position the button lower ... sizer_v2.Add((0, 225), 0, wx.ALL, 10) sizer_v2.Add(self.button, 0, wx.ALL, 10) sizer_v3.Add(self.radiobox2, 0, wx.ALL, 10) sizer_v3.Add(self.label2, 0, wx.LEFT|wx.RIGHT|wx.TOP, 10) sizer_v3.Add(self.edit2, 0, wx.LEFT|wx.RIGHT, 10) # put the 3 vertical sizers into the horizontal sizer sizer_h.Add(sizer_v1, 0) sizer_h.Add(sizer_v2, 0) sizer_h.Add(sizer_v3, 0) # it's the horizontal sizer you have to set self.SetSizer(sizer_h) # show present selection self.onAction(None) def onAction(self, event): """show the selected choice""" index1 = self.radiobox1.GetSelection() unit1 = self.options[index1] #print unit1 # test s = "Enter a value (%s):" % unit1 self.label1.SetLabel(s) # dito for radio box #2 index2 = self.radiobox2.GetSelection() unit2 = self.options[index2] #print unit2 # test s = "Result (%s):" % unit2 self.label2.SetLabel(s) value = float(self.edit1.GetValue()) factor1 = self.convD[unit1] factor2 = self.convD[unit2] result = factor2 * value/factor1 self.edit2.ChangeValue(str(result)) # these are the conversion dictionaries ... # (note that units won't appear in that order) distD ={} # all scale factors are relative to the first unit below distD['meter'] = 1.0 distD['micron'] = 1000000.0 distD['millimeter'] = 1000.0 distD['centimeter'] = 100.0 distD['kilometer'] = 0.001 distD['inch'] = 100.0/2.54 distD['foot'] = 100.0/30.48 distD['yard'] = 100.0/91.44 distD['mile'] = 0.001/1.609344 distD['rod'] = 1.0/5.029 areaD = {} # all scale factors are relative to the first unit below areaD['sq meter'] = 1.0 areaD['sq millimeter'] = 1000000.0 areaD['sq centimeter'] = 10000.0 areaD['sq kilometer'] = 0.000001 areaD['hectare'] = 0.0001 areaD['sq inch'] = 1550.003 areaD['sq foot'] = 10.76391 areaD['sq yard'] = 1.19599 areaD['acre'] = 0.0002471054 areaD['sq mile'] = 0.0000003861022 volD = {} # all scale factors are relative to the first unit below volD['cubic meter'] = 1.0 volD['microliter'] = 1000000000.0 volD['milliliter'] = 1000000.0 volD['liter'] = 1000.0 volD['pint(US)'] = 2113.376 volD['quart(US)'] = 1056.688 volD['gallon(US)'] = 264.172 volD['cubic inch'] = 61023.74 volD['cubic foot'] = 35.31467 volD['cubic yard'] = 1.307951 app = wx.App(1) MyNotebook(None, "testing wx.Notebook()", distD, areaD, volD).Show() app.MainLoop()
May 'the Google' be with you!
![]() |
Similar Threads
- Starting Python (Python)
- Autoupdater in wxPython (Python)
- what is python (Python)
Other Threads in the Python Forum
- Previous Thread: Threading & Thread: speed performance between modules
- Next Thread: merging 2 jpeg file into one file
Views: 50800 | Replies: 130
| Thread Tools | Search this Thread |
Tag cloud for examples, gui, python, wxpython
6 abrupt address advanced advice aliased apax automation avogadro beginner c++ chatprogramusingobjects class client code convert corners cturtle curves dan08 def development dragging dynamic edit editor enter error event examples excel exe file filename function graphics gui http iframe input java keyboard keyword linux list lists loan maze microsoft movingimageswithpygame mysql mysqlquery newb numbers panel parameters path problem program programming progressbar projects py py-mailer py2exe pygame pygtk pysimplewizard python random recursion recursive redirect rpg ruby search server signal silverlight simple smtp sqlite string sum table text thread threading tkinter tlapse tutorial ubuntu urllib urllib2 valueerror variable ventrilo windows wordgame wxpython







