| | |
Starting wxPython (GUI code)
![]() |
Just a quick look at wx.Timer(), wxPython's own timer action. There are two options a one_shot type and a continuous restart type action. Let's take a look at each ...
... and ...
python Syntax (Toggle Plain Text)
# a wx.Timer() one_shot example (delays for a set time) ... 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.timer = wx.Timer(self) # interval = 2000ms (2 seconds) # default is oneShot=False, timer keeps restarting self.timer.Start(2000, oneShot=True) # 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() app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'change colour from red to green after 2 seconds', (640, 180)).Show() app.MainLoop()
python Syntax (Toggle Plain Text)
# a wx.Timer() continuous restart example ... 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.red_flag = True self.timer = wx.Timer(self) # interval = 2000ms (2 seconds) # default is oneShot=False, timer keeps restarting # stop the timer action with self.timer.Stop() self.timer.Start(2000, oneShot=False) # bind EVT_TIMER event to self.onTimer() action self.Bind(wx.EVT_TIMER, self.onTimer) def onTimer(self, event): if self.red_flag: # establish new color self.SetBackgroundColour('green') self.red_flag = False else: self.SetBackgroundColour('red') self.red_flag = True # clear old color, set to new color self.ClearBackground() app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'flip colour from red to green every 2 seconds', (640, 180)).Show() app.MainLoop()
Last edited by vegaseat; Jul 21st, 2008 at 6:32 pm.
May 'the Google' be with you!
This short code sample shows how to add an exit confirm to your wxPython program, from either a menu exit or the title bar exit:
Zoe
python Syntax (Toggle Plain Text)
# confirm exit of a wxPython program import wx class MyFrame(wx.Frame): def __init__(self, parent, mytitle, mysize): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize) # create a status bar at the bottom self.CreateStatusBar() self.SetStatusText("Click on File") menu = wx.Menu() # just one item to test exit confirm # the optional & allows you to use alt/x # the last string argument shows in the status bar on mouse_over menu_exit = menu.Append(wx.ID_ANY, "E&xit", "Exit 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 self.Bind(wx.EVT_MENU, self.onMenuExit, menu_exit) # responds to exit symbol x on frame title bar self.Bind(wx.EVT_CLOSE, self.onCloseWindow) def onMenuExit(self, event): # triggers wx.EVT_CLOSE event and hence onCloseWindow() self.Close(True) def onCloseWindow(self, event): # dialog to verify exit dlg = wx.MessageDialog(self, "Want to exit?", "Exit", wx.YES_NO|wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: self.Destroy() dlg.Destroy() app = wx.App(0) # create the MyFrame instance and then show the frame MyFrame(None, 'Confirm exit', (400, 300)).Show() app.MainLoop()
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
The wx.TextCtrl() widget is used to enter single line text, password text, or multiline text. It can also be used to display multline text as a scrolled output widget, editable (default) or readonly. Under Windows you can also output text in the richedit format. Here is a short example ...
python Syntax (Toggle Plain Text)
# testing wxPython's # wx.TextCtrl(parent, id, value, pos, size, style) # a widget used for written text data input or output 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 your name below:" edit_label = wx.StaticText(self, wx.ID_ANY, s) self.edit = wx.TextCtrl(self, wx.ID_ANY, value="", size=(200, 20)) # respond to enter key when focus is on edit1 self.edit.Bind(wx.EVT_TEXT_ENTER, self.onAction) s = "Enter your password below:" pw_label = wx.StaticText(self, wx.ID_ANY, s) self.pw = wx.TextCtrl(self, wx.ID_ANY, value="", size=(200, 20), style=wx.TE_PASSWORD) self.pw.SetBackgroundColour("green") # respond to enter key when focus is on edit1 self.pw.Bind(wx.EVT_TEXT_ENTER, self.onAction) # create another text control for scrolled multiline output self.text_out = wx.TextCtrl(self, wx.ID_ANY, value="", size=(200, 70), style=wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY) sizer_v = wx.BoxSizer(wx.VERTICAL) sizer_v.Add(edit_label, 0, flag=wx.LEFT|wx.TOP|wx.EXPAND, border=10) sizer_v.Add(self.edit, 0, flag=wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, border=10) sizer_v.Add(pw_label, 0, flag=wx.LEFT|wx.TOP|wx.EXPAND, border=10) sizer_v.Add(self.pw, 0, flag=wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, border=10) sizer_v.Add(self.text_out, 0, flag=wx.ALL|wx.EXPAND, border=10) self.edit.SetFocus() self.SetSizer(sizer_v) def onAction(self, event): """ some action code""" name = self.edit.GetValue() s1 = "You entered the name: " + name + '\n' pw = self.pw.GetValue() if pw: s2 = "Your entered password: " + pw + '\n' s3 = "..... done!" else: s2 = s3 = "" self.pw.SetFocus() # text output to first, second and third line # play with this to your satisfaction self.text_out.ChangeValue(s1) self.text_out.AppendText(s2) self.text_out.AppendText(s3) app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'testing wx.TextCtrl() part1', (300, 250)).Show() app.MainLoop()
May 'the Google' be with you!
Just a few experiments with wxPython's label widget. It goes under the name of wx.StaticText ...
python Syntax (Toggle Plain Text)
# experiment with wxPython's # wx.StaticText(parent, id, label, pos, size, style) # used for labels to display information or results """ style: wx.ALIGN_LEFT Align the text to the left (default) wx.ALIGN_RIGHT Align the text to the right wx.ALIGN_CENTRE Center the text (horizontally) wx.ST_NO_AUTORESIZE Cancel the default of autosizing label to fit text """ import wx class MyFrame(wx.Frame): def __init__(self, parent, mytitle, mysize): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize) # note: label will try to autosize to fit text text = "What time does the two o'clock bus leave?" label1 = wx.StaticText(self, wx.ID_ANY, text) # set background and text colour of label1 label1.SetBackgroundColour("yellow") label1.SetForegroundColour("red") # note: text that does not fit on one line will wrap label2 = wx.StaticText(self, wx.ID_ANY, text) # set background and text colour label2 label2.SetBackgroundColour("blue") label2.SetForegroundColour("yellow") # set the font of label2 # type: wxDEFAULT, wxDECORATIVE, wxROMAN, wxSCRIPT, wxSWISS, wxMODERN # slant: wxNORMAL, wxSLANT or wxITALIC # weight: wxNORMAL, wxLIGHT or wxBOLD label2.SetFont(wx.Font(22, wx.MODERN, wx.SLANT, wx.BOLD)) label3 = wx.StaticText(self, wx.ID_ANY, "", style=wx.ALIGN_CENTRE) # set the background colour # text colour defaults to black label3.SetBackgroundColour("white") # set text for label3 to label2's text # does not copy colours or font label3.SetLabel(label2.GetLabel()) label4 = wx.StaticText(self, wx.ID_ANY, text, style=wx.ALIGN_RIGHT) # set the foreground/text colour # background defaults to system setting label4.SetForegroundColour("white") # use a box sizer to position the labels vertically sizer_v = wx.BoxSizer(wx.VERTICAL) # label1 and label2 proportions are set to fill space ratio 1:2 # also keeps ratio on frame stretch sizer_v.Add(label1, proportion=1, flag=wx.EXPAND) sizer_v.Add(label2, proportion=2, flag=wx.EXPAND) sizer_v.Add(label3, proportion=0, flag=wx.EXPAND) sizer_v.Add(label4, proportion=0, flag=wx.EXPAND) self.SetSizer(sizer_v) app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'test wx.StaticText()', (400, 300)).Show() app.MainLoop()
Last edited by vegaseat; Jul 25th, 2008 at 3:50 pm.
May 'the Google' be with you!
Shows you how to drag one of wxPython's widgets with the mouse pointer:
python Syntax (Toggle Plain Text)
# use mouse to drag the wx.Panel() widget # wx.Panel(parent, id, pos, size, style) import wx class MyFrame(wx.Frame): def __init__(self, parent, mytitle, mysize): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize) # needed for better control panel = wx.Panel(self) panel.SetBackgroundColour("green") self.drag_panel = wx.Panel(panel, size=(230, 100)) self.drag_panel.SetBackgroundColour("yellow") text1 = "point the mouse on the yellow panel \n" text2 = "press the left mouse button and drag it" wx.StaticText(panel, wx.ID_ANY, text1+text2, pos=(10, 150)) # bind mouse events to some actions self.drag_panel.Bind(wx.EVT_LEFT_DOWN, self.on_left_down) self.drag_panel.Bind(wx.EVT_LEFT_UP, self.on_left_up) self.drag_panel.Bind(wx.EVT_MOTION, self.on_motion) def on_left_down(self, event): self.drag_panel.CaptureMouse() x, y = self.drag_panel.ClientToScreen(event.GetPosition()) originx, originy = self.drag_panel.GetPosition() dx = x - originx dy = y - originy self.mp_delta = ((dx, dy)) def on_left_up(self, event): if self.drag_panel.HasCapture(): self.drag_panel.ReleaseMouse() def on_motion(self, event): if event.Dragging() and event.LeftIsDown(): x, y = self.drag_panel.ClientToScreen(event.GetPosition()) move_xy = (x - self.mp_delta[0], y - self.mp_delta[1]) self.drag_panel.Move(move_xy) app = wx.App() # create the MyFrame instance and show the frame MyFrame(None, 'drag the panel with the mouse', (400, 300)).Show() app.MainLoop()
Should you find Irony, you can keep her!
The information a statusbar can display can come handy:
python Syntax (Toggle Plain Text)
# set up a customized statusbar with three display fields # a statusbar is typically an information line at the bottom of a window import wx import time class MyFrame(wx.Frame): def __init__(self, parent, mytitle, mysize): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize) # fill the top part with a panel panel = wx.Panel(self, wx.ID_ANY, style=wx.SUNKEN_BORDER) panel.SetBackgroundColour("blue") self.sb = wx.StatusBar(self, wx.ID_ANY) # set the status bar with three fields self.sb.SetFieldsCount(3) # set an absolute status field width in pixels # (negative indicates a variable width field) self.sb.SetStatusWidths([-1, -1, -1]) self.SetStatusBar(self.sb) # put some text into field 0 (most left field) self.sb.SetStatusText("some text in field 0", 0) self.sb.SetStatusText("some text in field 1", 1) # use a timer to drive a date/time string in field 3 # here the most right field of the statusbar self.timer = wx.PyTimer(self.onUpdate) # update every 1000 milliseconds self.timer.Start(1000) self.onUpdate() def onUpdate(self): t = time.localtime(time.time()) st = time.strftime("%d-%b-%Y %I:%M:%S", t) # put date/time display string into field 2 self.sb.SetStatusText(st, 2) app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'test the wx.StatusBar', (460, 300)).Show() app.MainLoop()
drink her pretty
The wx.media.MediaCtrl() is wxPython's answer to playing a fair number of sound and video file formats. Here is an example of how to use this versatile widget ...
python Syntax (Toggle Plain Text)
# experiment with wxPython's # wx.media.MediaCtrl(parent, id, pos, size, style, szBackend) # the backend is usually figured out by the control itself # wx.MEDIABACKEND_DIRECTSHOW Windows # wx.MEDIABACKEND_QUICKTIME Mac OS X # wx.MEDIABACKEND_GSTREAMER Linux import wx import wx.media import os class MyFrame(wx.Frame): def __init__(self, parent, mytitle, mysize): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize) self.SetBackgroundColour("green") # check if the media control is implemented try: self.mc = wx.media.MediaCtrl(self, style=wx.SIMPLE_BORDER) except NotImplementedError: self.Destroy() raise loadButton = wx.Button(self, wx.ID_ANY, "Load File") self.Bind(wx.EVT_BUTTON, self.onLoadFile, loadButton) playButton = wx.Button(self, wx.ID_ANY, "Play") playButton.SetToolTip(wx.ToolTip("load a file first")) self.Bind(wx.EVT_BUTTON, self.onPlay, playButton) pauseButton = wx.Button(self, wx.ID_ANY, "Pause") pauseButton.SetToolTip(wx.ToolTip("press Play to resume")) self.Bind(wx.EVT_BUTTON, self.onPause, pauseButton) stopButton = wx.Button(self, wx.ID_ANY, "Stop") stopButton.SetToolTip(wx.ToolTip("also resets to start")) self.Bind(wx.EVT_BUTTON, self.onStop, stopButton) self.slider = wx.Slider(self, wx.ID_ANY, 1000000, 0, 1000000, size=(380, -1), style=wx.SL_HORIZONTAL|wx.SL_AUTOTICKS|wx.SL_LABELS) self.slider.Bind(wx.EVT_SLIDER, self.onSeek) ext = " load .mp3 .mpg .mid .wav .au or .avi files" self.st_info = wx.StaticText(self, wx.ID_ANY, ext, size=(300,-1)) # use a gridbagsizer to layout widgets sizer = wx.GridBagSizer(vgap=5, hgap=5) # pos=(row, column) # span=(rowspan, columnspan) sizer.Add(loadButton, pos=(1,1)) sizer.Add(self.st_info, pos=(1,2), span=(1,2)) sizer.Add(self.slider, pos=(2,1), span=(2,3)) sizer.Add(playButton, pos=(4,1)) sizer.Add(pauseButton, pos=(4,2)) sizer.Add(stopButton, pos=(4,3)) # for .avi .mpg video files use this lower grid area sizer.Add(self.mc, pos=(5,1), span=(7,3)) self.SetSizer(sizer) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.onTimer) # update every 100 milliseconds self.timer.Start(100) def onLoadFile(self, evt): mask = "MP3 (.mp3)|*.mp3|MPG (.mpg)|*.mpg|All (.*)|*.*" dlg = wx.FileDialog(self, message="Choose a media file", defaultDir=os.getcwd(), defaultFile="", wildcard=mask, style=wx.OPEN|wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.doLoadFile(path) dlg.Destroy() def doLoadFile(self, path): if not self.mc.Load(path): wx.MessageBox("Unable to load %s: Unsupported format?" % path, "ERROR", wx.ICON_ERROR|wx.OK) else: folder, self.filename = os.path.split(path) self.st_info.SetLabel(" %s" % self.filename) self.mc.SetInitialSize() self.GetSizer().Layout() # set the slider range min to max self.slider.SetRange(0, self.mc.Length()) self.mc.Play() def onPlay(self, evt): self.slider.SetRange(0, self.mc.Length()) s1 = " %s" % self.filename s2 = " size: %s ms" % self.mc.Length() s3 = " (%d seconds)" % (self.mc.Length()/1000) self.st_info.SetLabel(s1+s2+s3) self.mc.SetInitialSize() self.GetSizer().Layout() self.mc.Play() def onPause(self, evt): self.mc.Pause() def onStop(self, evt): self.mc.Stop() def onSeek(self, evt): """allows dragging the slider pointer to this position""" offset = self.slider.GetValue() self.mc.Seek(offset) def onTimer(self, evt): """moves the slider pointer""" offset = self.mc.Tell() self.slider.SetValue(offset) app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'Play Audio and Video', (420, 400)).Show() app.MainLoop()
May 'the Google' be with you!
If you need to enter a date, wxPython has a special widget for such a thing. It's quite versatile and safeguards against the entry of inappropriate dates. This little code example lets you find out how many shopping days you have till xmas, or how many days old you are amongst other things. Read the displayed text and play with the wx.DatePickerCtrl() to get familiar with its capabilities ...
python Syntax (Toggle Plain Text)
# test wxPython's # wx.DatePickerCtrl(parent, id, dt, pos, size, style) # dt = initial date (today by default) import wx import datetime as dt class MyFrame(wx.Frame): def __init__(self, parent, mytitle, mysize): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize) self.SetBackgroundColour("yellow") s1 = "You can click on the month, day or year portion \n" s2 = "of the displayed date and use the keyboard up down \n" s3 = "arrows to change the highlighted part. \n" s4 = " Or simply type the change in to replace the high- \n" s5 = "lighted part (will not acccept impossible dates). \n" s6 = " Or you can click on the right side drop marker to \n" s7 = "show a monthly calendar and change the date that way." info = s1+s2+s3+s4+s5+s6+s7 info_label = wx.StaticText(self, wx.ID_ANY, info, pos=(20, 10)) # create input widgets self.datepick = wx.DatePickerCtrl(self, wx.ID_ANY, pos=(20, 110), style=wx.DP_DROPDOWN|wx.DP_SHOWCENTURY) # bind mouse click to an action self.datepick.Bind(wx.EVT_DATE_CHANGED, self.onAction) # create an output widget self.label = wx.StaticText(self, wx.ID_ANY, "", pos=(20, 140)) def onAction(self, event): """ some action code""" # returned object is type wx._misc.DateTime selected = self.datepick.GetValue() month = selected.Month + 1 day = selected.Day year = selected.Year # you could do this ... # date_str = "%02d/%02d/%4d" % (month, day, year) # ... or do some date math with module datetime date = dt.date(year, month, day) date_str = date.strftime("%m/%d/%Y") today = dt.date.today() age = date - today s = " (%d days from today)" % age.days self.label.SetLabel("Date selected = " + date_str + s) app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'testing wx.DatePickerCtrl()', (320, 210)).Show() app.MainLoop()
Last edited by vegaseat; Aug 2nd, 2008 at 11:02 pm. Reason: a
May 'the Google' be with you!
This is an example how to create a wx.Frame() that fills the entire display screen:
python Syntax (Toggle Plain Text)
# wx.DisplaySize() gives (width, height) tuple of your display screen import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, pos=(0, 0), size=wx.DisplaySize()) self.SetBackgroundColour('blue') s = "Frame has full display size of %d x %d" % wx.DisplaySize() self.SetTitle(s) app = wx.App(0) # instantiate class MyFrame and show MyFrame().Show(True) app.MainLoop()
drink her pretty
Here is a way to fill your full display screen with a wx.Frame() widget, that does not show a border nor a title bar. You have to give it an exit button of your own. To be mildly playful, lets cycle through the wxPython colour data base at random:
python Syntax (Toggle Plain Text)
# a full screen-display wx.Frame without border and title bar # wxPython's wx.lib.colourdb contains about 630 different # colour names to cycle through at random import wx import random import wx.lib.colourdb as cdb class MyFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, wx.ID_ANY) # create a full screen display frame, no title bar self.ShowFullScreen(True, style=wx.FULLSCREEN_ALL) w, h = wx.DisplaySize() # create a panel to easily refresh colours self.panel = wx.Panel(self, wx.ID_ANY, size=(w, h)) # supply an exit button in the upper right corner self.exitbutton = wx.Button(self.panel, wx.ID_ANY, label='X', pos=(w - 25, 5), size=(20, 15)) self.exitbutton.Bind(wx.EVT_BUTTON, self.exitbuttonClick) cdb.updateColourDB() # create a list of all the colours in the colour data base self.colours = cdb.getColourList() self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.onTimer, self.timer) # change colour every second (1000ms) self.timer.Start(1000) def onTimer(self, event): bg = random.choice(self.colours) #print bg # test self.panel.SetBackgroundColour(bg) self.panel.Refresh() def exitbuttonClick(self, event): self.Close(True) app = wx.App(0) MyFrame(None).Show(True) app.MainLoop()
drink her pretty
![]() |
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 |
abrupt accessdenied ansi anti apache application approximation argv array backend beginner binary builtin calculator change converter countpasswordentry curved dan08 dictionaries dictionary dynamic edit enter file float format function heads homework import inches input java keyboard lapse library line lines linux list lists loop microphone mouse movingimageswithpygame mysqlquery newb number numbers numeric output parameters parsing path phonebook plugin pointer prime programming progressbar py2exe pygame pyopengl python random recursion redirect remote reverse scrolledtext session simple software sprite statictext statistics string strings syntax table terminal text textarea thread threading time tlapse trick tuple tutorial twoup ubuntu unicode unit urllib urllib2 variable wordgame wxpython






