| | |
Starting wxPython (GUI code)
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
I think we may have talked about this before, but I can't find it. Here is a way to use a sound file inside the Python code and play it. First create a base64 encoded string of the binary sound file:
Now you can transfer the result to your Python program and play the sound without having to attach the sound file:
python Syntax (Toggle Plain Text)
# create a base64 encoded string from binary sound data # and limit the length of each data line to n characters # ene import base64 def text_lines(data, n): """ write a long one line text as lines of n char each """ s = "" for ix, c in enumerate(data): if ix % n == 0 and ix != 0: s += c + '\n' else: s += c return s # pick a wave file that is in the working folder wave_file = "pop.wav" # this is a binary read data = base64.b64encode(open(wave_file, 'rb').read()) data = text_lines(data, 70) print "wav_base64='''\\\n" + data + "'''" """ highlight and copy the resulting base64 wav string to embed in program code, use wav = base64.b64decode(wav_base64) to decode to binary data: wav_base64='''\ UklGRuABAABXQVZFZm10IBAAAAABAAEAESsAABErAAABAAgAZGF0YbsBAACAgICAgICAgIC AgICAfX12aVtQS0hJSk5TZpWyv8LBwMC/vry2nWxLPTs9PT5AR05pn77BwcC/vruxlGtJP T09PkBHU3qrv8DAv7+7tKiGWUA8PT4+Qk1tm7fAv7++ubKmhl1CPD0+P0NPbZayv8C/vbe vooNdRD0+PkBIWXWVrru/vbmypo5uU0I+P0NLWG6JorO7vLm0rJyBZlBEQkNIUF5xiJ2wu bq4s6qZg21ZTUhITFRhcoaaqLGzsayilIFvYFVQUFNZY29/j52orKunnpKFdmheWFVWWmF seYiXoqmrqaKXi390amRfXmBka3aDj5ifoqGemZGIfXJpY2FiZmx0fYePlpqcmpSNhHpyb Wloam91foaNk5eXlZGMhH12b2xqam1xd32Ei5CVlpSPiYF6dHFvbnByd36Fi4+SkY6KhoN +end3d3h8gYaKjIyMioeDf3t4dnZ3eX2BhYiKi4uJhoJ+eXZ1dnd6fICFiY2PjoyHgnx3d XNzdHZ6f4WKjpCPjIiEf3t3dHNzdXh8goeLjY2NiYWBfHh0cnJzdnl9gYSGh4aFg398eXd 2d3l8foCChIaIh4aEgQA=''' """
python Syntax (Toggle Plain Text)
# playing a base64 encoded wave sound string with wxPython's # wx.SoundFromData(sound_data) and sound.Play() # ene import wx import base64 class MyFrame(wx.Frame): def __init__(self, parent, mytitle, mysize, sound_data): wx.Frame.__init__(self, parent, -1, mytitle, size=mysize) self.SetBackgroundColour("blue") # use a small delay to display the frame before sound starts wx.FutureCall(100, self.play_sound) def play_sound(self): sound = wx.SoundFromData(sound_data) # wx.SOUND_SYNC --> sound plays completely through for k in range(10): sound.Play(wx.SOUND_SYNC) wav_base64='''\ UklGRuABAABXQVZFZm10IBAAAAABAAEAESsAABErAAABAAgAZGF0YbsBAACAgICAgICAgIC AgICAfX12aVtQS0hJSk5TZpWyv8LBwMC/vry2nWxLPTs9PT5AR05pn77BwcC/vruxlGtJP T09PkBHU3qrv8DAv7+7tKiGWUA8PT4+Qk1tm7fAv7++ubKmhl1CPD0+P0NPbZayv8C/vbe vooNdRD0+PkBIWXWVrru/vbmypo5uU0I+P0NLWG6JorO7vLm0rJyBZlBEQkNIUF5xiJ2wu bq4s6qZg21ZTUhITFRhcoaaqLGzsayilIFvYFVQUFNZY29/j52orKunnpKFdmheWFVWWmF seYiXoqmrqaKXi390amRfXmBka3aDj5ifoqGemZGIfXJpY2FiZmx0fYePlpqcmpSNhHpyb Wloam91foaNk5eXlZGMhH12b2xqam1xd32Ei5CVlpSPiYF6dHFvbnByd36Fi4+SkY6KhoN +end3d3h8gYaKjIyMioeDf3t4dnZ3eX2BhYiKi4uJhoJ+eXZ1dnd6fICFiY2PjoyHgnx3d XNzdHZ6f4WKjpCPjIiEf3t3dHNzdXh8goeLjY2NiYWBfHh0cnJzdnl9gYSGh4aFg398eXd 2d3l8foCChIaIh4aEgQA=''' sound_data = base64.b64decode(wav_base64) app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'wx.SoundFromData()', (300, 100), sound_data).Show() app.MainLoop()
Last edited by Ene Uran; Jun 13th, 2009 at 7:49 pm.
drink her pretty
I was doing a search on Daniweb for 'wx.AboutBox()', but it simply did not select a post, only the whole thread. So, this may be already somewhere. I am testing wxPython's fancy wx.AboutBox widget:
python Syntax (Toggle Plain Text)
# testing the fancy wx.AboutBox() widget # snee import wx from wx.lib.wordwrap import wordwrap class MyFrame(wx.Frame): """ create a frame, with a menu, statusbar and 2 about dialogs """ def __init__(self): # create a frame/window, no parent, default to wxID_ANY wx.Frame.__init__(self, None, wx.ID_ANY, "wx.AboutBox test", pos=(300, 150), size=(300, 350)) self.SetBackgroundColour("brown") # create a status bar at the bottom self.CreateStatusBar() self.SetStatusText("Click on File") menu = wx.Menu() # the optional & allows you to use alt/a # the last string argument shows in the status bar on mouse_over menu_about = menu.Append(wx.ID_ANY, "&About", "Ho-hum about box") menu_about2 = menu.Append(wx.ID_ANY, "About&2", "Fancy about box") menu.AppendSeparator() # the optional & allows you to use alt/x menu_exit = menu.Append(wx.ID_ANY, "E&xit", "Quit the program") # create a menu bar at the top menuBar = wx.MenuBar() # the & allows you to use alt/f menuBar.Append(menu, "&File") self.SetMenuBar(menuBar) # bind the menu events to an action/function/method self.Bind(wx.EVT_MENU, self.onMenuAbout, menu_about) self.Bind(wx.EVT_MENU, self.onMenuAbout2, menu_about2) self.Bind(wx.EVT_MENU, self.onMenuExit, menu_exit) def onMenuAbout(self, event): """a somewhat ho-hum about box""" 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 onMenuAbout2(self, event): """use the much fancier wx.AboutBox()""" # first fill the info object info = wx.AboutDialogInfo() # Name and Version show in larger font info.Name = "Bratwurst7" info.Version = "v.1.7.4" info.Copyright = "(C) copyfight 2008" info.Description = wordwrap( "The Bratwurst7 program is a software program that " "makes you desire a freshly grilled bratwurst and " "a good German beer right now! Teaching programmers " "everywhere to be aware of those hidden immediate " "inner desires!", 300, wx.ClientDC(self)) info.WebSite = ("http://en.wikipedia.org/wiki/Bratwurst", "Bratwurst7 home") info.Developers = ["Carl Arm", "Carol Bein", "Candy Kisser"] info.License = "Wish upon a star!" # now call wx.AboutBox with this info object wx.AboutBox(info) def onMenuExit(self, event): self.Close(True) app = wx.App() # create the MyFrame class instance, then show the frame MyFrame().Show() app.MainLoop()
No one died when Clinton lied.
This code shows how to create a custom pop-up dialog for text entry ...
python Syntax (Toggle Plain Text)
# using wxPython's # wx.Dialog(parent, id, title, pos, size, style, name="dialogBox") # to create a custom text entry pop-up dialog # 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("green") # call the dialog or input widget self.button = wx.Button(self, -1, label='Get the name', pos=(20, 20)) # bind mouse or key event to an action self.button.Bind(wx.EVT_BUTTON, self.onAction) # create an output widget self.result = wx.TextCtrl(self, -1, value="", pos=(20, 70), size=(200, 120), style=wx.TE_MULTILINE|wx.HSCROLL) def onAction(self, event): """call the pop-up dialog and get the string entered""" dlg = MyDialog(self, 'Text Entry', 'Enter your name:') if dlg.ShowModal() == wx.ID_OK: # note, parent has been assigned dialog's entry instance self.name = self.entry.GetValue() self.result.AppendText(self.name + '\n') dlg.Destroy() class MyDialog(wx.Dialog): def __init__(self, parent, mytitle, msg): wx.Dialog.__init__(self, parent, -1, mytitle, size=(250,180)) entry = wx.TextCtrl(self, -1, value="", size=(200, 20)) # assign dialog's entry instance to parent parent.entry = entry button_ok = wx.Button(self, wx.ID_OK) button_cancel = wx.Button(self, wx.ID_CANCEL) sizer = self.CreateTextSizer(' ' + msg) sizer.Add(entry, 0, wx.ALL, 5) sizer.Add(button_ok, 0, wx.ALL, 5) sizer.Add(button_cancel, 0, wx.ALL, 5) self.SetSizer(sizer) app = wx.App(0) # create a MyFrame instance and show the frame mytitle = 'custom entry dialog' width = 300 height = 260 MyFrame(None, mytitle, (width, height)).Show() app.MainLoop()
Last edited by vegaseat; Jul 17th, 2009 at 10:48 pm.
May 'the Google' be with you!
Here we use the simple wx.lib.filebrowsebutton.FileBrowseButton() to load and show an image ...
python Syntax (Toggle Plain Text)
# experiment with wxPython's # wx.StaticBitmap(parent, id=-1, bitmap, pos=wx.DefaultPosition, # size=wx.DefaultSize, style=0, name="staticBitmap") # wx.lib.filebrowsebutton.FileBrowseButton(parent, labelText, # fileMask) # to load and show an image file # the frame expands to show the entire image # vegaseat import wx import wx.lib.filebrowsebutton as wxfbb class MyFrame(wx.Frame): def __init__(self, parent, mysize): wx.Frame.__init__(self, parent, -1, size=mysize) self.panel = wx.Panel(self) self.size = mysize # file browser masked to look for common image types mask ="*.gif; *.jpg; *.png; *.bmp" self.fbb = wxfbb.FileBrowseButton(self.panel, labelText="Select an image file:", fileMask=mask) self.button = wx.Button(self.panel, wx.ID_ANY, ">> Show") self.button.Bind(wx.EVT_BUTTON, self.load_image) # setup the layout with sizers hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(self.fbb, 1, wx.ALIGN_CENTER_VERTICAL) hsizer.Add(self.button, 0, wx.ALIGN_CENTER_VERTICAL) # create a border space border = wx.BoxSizer(wx.VERTICAL) border.Add(hsizer, 0, wx.EXPAND|wx.ALL, 10) self.panel.SetSizer(border) def load_image(self, event): image_file = self.fbb.GetValue() # hide the file browse panel self.panel.Hide() image = wx.Bitmap(image_file) image_size = image.GetSize() # set the frame size to fit the image size self.SetClientSize(image_size) # bitmap's upper left corner is frame pos=(0, 0) by default wx.StaticBitmap(self, wx.ID_ANY, image, size=image_size) # optionally show some image information in the frame title width, height = image_size depth = image.GetDepth() info = "%s %dx%dx%d" % (image_file, width, height, depth) self.SetTitle(info) app = wx.App(0) # create a MyFrame instance and show the frame mysize = (600, 200) MyFrame(None, mysize).Show() app.MainLoop()
May 'the Google' be with you!
The wxPython wx.lib.fancytext.StaticFancyText() class can display colorful text written in XML format:
python Syntax (Toggle Plain Text)
# wxPython's # wx.lib.fancytext.StaticFancyText(parent, id, text, ...) # can display text written in XML format # Henri import wx import wx.lib.fancytext as wxft class FancyText(wx.Panel): def __init__(self, parent, xml_text): wx.Panel.__init__(self, parent, -1) self.ftext = wxft.StaticFancyText(self, -1, text=xml_text, background=wx.Brush('black')) red = '<font family="swiss" color="red" size="48">' blue = '<font family="swiss" color="blue" size="48">' green = '<font family="swiss" color="green" size="48">' # match the 3 <font ...> tags with closing </font> tags xml_text = """\ %s Feeling %sblue? %s Or green with envy? </font> </font> </font> """ % (red, blue, green) app = wx.App(0) mytitle = 'wx.lib.fancytext.StaticFancyText()' mysize = (620, 220) frame = wx.Frame(None, -1, title=mytitle, size=mysize) FancyText(frame, xml_text) frame.Show() app.MainLoop()
Should you find Irony, you can keep her!
Example of wx.ScrolledWindow to display large area in one small frame:
python Syntax (Toggle Plain Text)
# test wx.ScrolledWindow(parent, id, pos, size, style) # with multiple widgets that exceed normal frame area # tested with Python 2.5.4 and wxPython 2.8.9.1 # Henri import wx class MyFrame(wx.Frame): def __init__(self, parent, mytitle): wx.Frame.__init__(self, parent, -1, mytitle, size=(400,300)) # create scrolled window # let the wx.ScrolledWindow fill the frame self.scrollw = wx.ScrolledWindow(self, wx.ID_ANY) self.scrollw.SetBackgroundColour('green') # set EnableScrolling(bool x_scrolling, bool y_scrolling) # default is self.scrollw.EnableScrolling(True, True) # if True, wx.ScrolledWindow shows its scroll bars # create the scroll bars, set the scrolling ranges (pixels) max_w = 1000 max_h = 1000 # SetScrollbars(pixelsPerUnitX, pixelsPerUnitY, noUnitsX, # noUnitsY) self.scrollw.SetScrollbars(20, 20, max_w//20, max_h//20) # pick something that needs area larger than the frame self.createMultiLabels() def createMultiLabels(self): """from one of vegaseat's example codes""" # things to put on the labels label_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ->UM' # wx.GridSizer(rows, cols, vgap, hgap) gsizer = wx.GridSizer(6, 5, 0, 0) # create list of labels # acccess with self.labels[0], self.labels[1] etc. self.labels = [] for c in label_string: # labels have of scroll window as parent self.labels.append(wx.StaticText(self.scrollw, -1, label=c, style=wx.ALIGN_CENTRE|wx.SUNKEN_BORDER)) # iterate through the list of labels and set # layout, optionally font and colour font = wx.Font(60, wx.MODERN, wx.NORMAL, wx.BOLD) for x in self.labels: x.SetFont(font) x.SetBackgroundColour("yellow") gsizer.Add(x, 0, flag=wx.ALL, border=20) # set the sizer in scroll window self.scrollw.SetSizer(gsizer) app = wx.App(0) # create MyFrame instance and show the frame MyFrame(None, "wx.ScrolledWindow for large display").Show() app.MainLoop()
Should you find Irony, you can keep her!
You can give your wxPython window nice custom icon:
python Syntax (Toggle Plain Text)
# experiment with wxPython's wx.Icon() and SetIcon() import wx class MyFrame(wx.Frame): """make a frame, inherits wx.Frame""" def __init__(self): wx.Frame.__init__(self, None, -1, 'wxPython custom icon', pos=wx.Point(300, 150), size=wx.Size(300, 350)) self.SetBackgroundColour('green') # pick icon file (.ico) you have ... #iconFile = "py.ico" # or 32x32 Windows .bmp file will do ... # (will miss mask if not rectangular image) icon_file = "Attention32x32.bmp" self.SetIcon(wx.Icon(icon_file, wx.BITMAP_TYPE_ICO)) # show the frame self.Show(True) application = wx.App(0) # call class MyFrame window = MyFrame() application.MainLoop()
Should you find Irony, you can keep her!
Hey Henri, thanks for reminding me that these multilables are a nice filler to force the scrollbars to show. Here I applied them to the scrolled panel ...
python Syntax (Toggle Plain Text)
# exploring wxPython's # wx.lib.scrolledpanel.ScrolledPanel(parent, id, pos, size, style) # default pos is (0, 0) and default size is (-1, -1) which fills the frame # the scrolled panel is an area on which other controls are placed # that can take more space then the parent frame has import wx import wx.lib.scrolledpanel class MyScrolledPanel(wx.lib.scrolledpanel.ScrolledPanel): def __init__(self, parent): # make the scrolled panel larger than its parent wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent, wx.ID_ANY, size=(600, 600), style=wx.TAB_TRAVERSAL) # scroll bars won't appear until required # default is SetupScrolling(scroll_x=True, scroll_y=True) self.SetupScrolling() self.SetBackgroundColour("blue") # these multilabels will force the scroll bars to show # as they exceed the size of the frame label_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ #@$' # wx.GridSizer(rows, cols, vgap, hgap) gsizer = wx.GridSizer(6, 5, 0, 0) # create a list of labels # acccess with self.labels[0], self.labels[1] etc. self.labels = [] for c in label_string: self.labels.append(wx.StaticText(self, wx.ID_ANY, label=c, style=wx.ALIGN_CENTRE)) # iterate through the list of labels and set layout # font and colour font = wx.Font(24, wx.MODERN, wx.NORMAL, wx.BOLD) for x in self.labels: x.SetFont(font) x.SetBackgroundColour("yellow") gsizer.Add(x, 0, flag=wx.ALL|wx.EXPAND, border=15) # set the sizer self.SetSizer(gsizer) app = wx.App(0) # create a frame, no parent, default ID, title, size caption = "ScrolledPanel" frame = wx.Frame(None, wx.ID_ANY, caption, size=(250, 310)) MyScrolledPanel(frame) frame.Center() frame.Show() app.MainLoop()
Last edited by vegaseat; Aug 29th, 2009 at 7:30 pm. Reason: spelling
May 'the Google' be with you!
If the user of your program has to select from a fixed list of choices, the wx.SingleChoiceDialog is a good way to go:
python Syntax (Toggle Plain Text)
# exploring the wx.SingleChoiceDialog # fish_list from: # http://allrecipes.com/Recipes/Seafood/Fish/Main.aspx # snee import wx class MyFrame(wx.Frame): def __init__(self, fish_list): wx.Frame.__init__(self, None, -1, 'wx.SingleChoiceDialog', size=(350, 100)) self.CreateStatusBar() label = wx.StaticText(self) dlg = wx.SingleChoiceDialog(None, "What's your favorite fish to eat?", 'Select a Fish', fish_list) if dlg.ShowModal() == wx.ID_OK: answer = dlg.GetStringSelection() # show the selected choice different ways ... sf = 'Your choice was: %s' % answer label.SetLabel(sf) self.SetStatusText(sf) self.SetTitle(sf) dlg.Destroy() fish_list = [ 'Catfish', 'Cod', 'Flounder', 'Haddock', 'Halibut', 'Mahi Mahi', 'Salmon', 'Snapper', 'Swordfish', 'Tilapia', 'Trout', 'Tuna' ] app = wx.App() frame = MyFrame(fish_list) frame.Center() frame.Show() app.MainLoop()
No one died when Clinton lied.
So you want to test drive some wxPython widgets without all that OOP stuff, here are some examples how to do this:
One more for the Gipper:
python Syntax (Toggle Plain Text)
# test a wxPython combobox selection import wx def combo_select(event): color = combo.GetValue() frame.SetTitle(color) app = wx.App(0) frame = wx.Frame(None, -1, "wx.ComboBox", size=(220, 40)) # set up the choices for the listbox part of the combobox choice_list = ['red', 'green', 'blue', 'yellow','white', 'magenta'] # create a combobox widget combo = wx.ComboBox( frame, -1, choices=choice_list) # set initial value combo.SetValue('red') # click on a dropdown choice to select it combo.Bind(wx.EVT_COMBOBOX, combo_select) frame.Center() frame.Show() app.MainLoop()
python Syntax (Toggle Plain Text)
# test wxPython checkbox selections import wx def on_action(event): s = "" if cb1.IsChecked(): s += "cb1 (red) is checked " if cb2.IsChecked(): s += "cb2 (blue) is checked " if not cb1.IsChecked() and not cb2.IsChecked(): s = "none is checked" frame.SetTitle(s) app = wx.App(0) frame = wx.Frame(None, -1, "wx.CheckBox", size=(450, 79)) cb1 = wx.CheckBox(frame, -1, 'red', pos=(10, 10)) cb2 = wx.CheckBox(frame, -1, 'blue', pos=(10, 40)) # set checkbox cb1 to checked cb1.SetValue(True) # bind checkbox mouse click to an action cb1.Bind(wx.EVT_CHECKBOX, on_action) cb2.Bind(wx.EVT_CHECKBOX, on_action) # initial call on_action(None) frame.Center() frame.Show() app.MainLoop()
Last edited by sneekula; Sep 15th, 2009 at 6:00 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: Do I need to upgrade Python?
- Next Thread: Text in Pygame for 2.6
| Thread Tools | Search this Thread |
6 abrupt address advanced anti apax applicaions array backend beginner bluetooth c++ calculator calling client code convert copy cx-freeze dan08 database dragging dynamic edit embed error event examples excel file filename forms function getvalue google graphics gui images input java launcher linux list lists loop microphone movingimageswithpygame numbers opensource output path phonebook problem programming progressbar projects push py py2exe pygame pygtk python rails random redirect remote return ruby rubyconf samples script shebang silverlight slicenotation statictext stop string strings sum table textfields thread threading tkinter tlapse toolbar tooltip tutorial ubuntu urllib urllib2 valueerror variable wikipedia windows wx.wizard wxpython xlwt xui xwnidow







