| | |
Starting wxPython (GUI code)
![]() |
Trapping a key event:
python Syntax (Toggle Plain Text)
# bind keyevent to key down and display the key value import wx class KeyEvent(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(400, 70)) self.SetBackgroundColour("yellow") # create a label self.label = wx.StaticText(self, wx.ID_ANY, label=" ", pos=(20, 30)) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) self.Show(True) def OnKeyDown(self, event): keycode = event.GetKeyCode() s = "Key value = " + str(keycode) self.label.SetLabel(s) if keycode == wx.WXK_ESCAPE: choice = wx.MessageBox('Are you sure you want to quit? ', 'Question', wx.YES_NO|wx.CENTRE|wx.NO_DEFAULT, self) if choice == wx.YES: self.Close() event.Skip() app = wx.App() KeyEvent(None, wx.ID_ANY, 'press any key (press escape to exit)') app.MainLoop()
drink her pretty
Sneekula left one small starter editor somewhere around DaniWeb. So I took it and modified it to use the wxPython toolbar with icon images rather than Snee's menu bar. The images come from wxPython's builtin art library:
python Syntax (Toggle Plain Text)
# the start of one small text editor with toolbar and image icons # notice that the wx.TextCtrl() surface has already some advanced # features: select text, right click to cut, copy and paste etc. import os import wx class MyFrame(wx.Frame): def __init__(self, title): wx.Frame.__init__(self, None, wx.ID_ANY, title, size=(500, 300)) self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE) # statusBar at the bottom of the window self.CreateStatusBar() self.SetStatusText(" Click on the icon") # ToolBar at the top of the window toolbar = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL|wx.NO_BORDER) toolbar.SetToolBitmapSize(size=(24,24)) toolbar.AddSimpleTool(wx.ID_OPEN, self.getBMP(wx.ART_FILE_OPEN), "Load", " Load a text file") toolbar.AddSimpleTool(wx.ID_SAVE, self.getBMP(wx.ART_FILE_SAVE), "Save", " Save the text file") toolbar.AddSimpleTool(wx.ID_ABOUT, self.getBMP(wx.ART_INFORMATION), "About"," About message") toolbar.AddSeparator() toolbar.AddSimpleTool(wx.ID_EXIT, self.getBMP(wx.ART_QUIT), "Exit"," Exit the program") toolbar.Realize() self.SetToolBar(toolbar) # bind the various toolbar icon click events to some action self.Bind(wx.EVT_TOOL, self.onLoad, id=wx.ID_OPEN) self.Bind(wx.EVT_TOOL, self.onSave, id=wx.ID_SAVE) self.Bind(wx.EVT_TOOL, self.onAbout, id=wx.ID_ABOUT) self.Bind(wx.EVT_TOOL, self.onExit, id=wx.ID_EXIT) def getBMP(self, pic_id): """get the bitmap image from the wxPython art provider""" return wx.ArtProvider.GetBitmap(pic_id, wx.ART_TOOLBAR, wx.Size(24, 24)) def onAbout(self, e): """ the about box """ about = wx.MessageDialog( self, " A very simple text editor \n" " using the wxPython GUI toolkit", "About Simple Editor", wx.OK) about.ShowModal() about.Destroy() def onLoad(self, e): """ open text file""" self.dirname = '' mask = "Text (.txt)|*.txt|All (.*)|*.*" dlg = wx.FileDialog(self, "Choose a file to load", self.dirname, "", mask, wx.OPEN) if dlg.ShowModal() == wx.ID_OK: self.filename = dlg.GetFilename() self.dirname = dlg.GetDirectory() f = open(os.path.join(self.dirname,self.filename),'r') self.control.SetValue(f.read()) f.close() dlg.Destroy() def onSave(self, e): """ Save text file""" self.dirname = '' mask = "Text (.txt)|*.txt|All (.*)|*.*" dlg = wx.FileDialog(self, "Choose or create a file to save to", self.dirname, self.filename, mask, wx.OVERWRITE_PROMPT|wx.OPEN) if dlg.ShowModal() == wx.ID_OK: self.filename = dlg.GetFilename() self.dirname = dlg.GetDirectory() f = open(os.path.join(self.dirname,self.filename),'w') f.write(self.control.GetValue()) f.close() dlg.Destroy() def onExit(self, e): self.Close(True) app = wx.App(0) # create instance of MyFrame and show it MyFrame(title="A Simple Editor").Show() app.MainLoop()
Last edited by vegaseat; Jul 31st, 2008 at 11:49 pm. Reason: small blemish, error in onSave
Should you find Irony, you can keep her!
This shows you how to use wxPython's wx.lib.fancytext to show super and subscripted text in a specified font, colour and size. The text coding is XML ...
python Syntax (Toggle Plain Text)
# wxPython's wx.lib.fancytext can show super and subscripted text # using XML code import wx import wx.lib.fancytext as fancytext class FancyText(wx.Panel): """display fancytext on a panel""" def __init__(self, parent): wx.Panel.__init__(self, parent, wx.ID_ANY) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnPaint(self, evt): """generate the fancytext on a paint dc canvas""" dc = wx.PaintDC(self) fancytext.RenderToDC(xml_str, dc, 0, 20) # the XML code string xml_str = """\ <font family="swiss" color="blue" size="20"> H<sub>2</sub>O x<sup>3</sup> + y<sup>2</sup> - 15 = 0 </font> """ app = wx.App(0) frame = wx.Frame(None, wx.ID_ANY, title='wxPython fancy text', pos=(100, 50), size=(500, 250)) FancyText(frame) frame.Show(True) app.MainLoop()
May 'the Google' be with you!
Dealing with mouse events ...
python Syntax (Toggle Plain Text)
# get the position of the mouse when clicked or moved import wx class MyFrame(wx.Frame): """create a color frame, inherits from wx.Frame""" def __init__(self, parent): wx.Frame.__init__(self, parent, wx.ID_ANY, "Move or click mouse") self.SetBackgroundColour('Goldenrod') # give it a fancier cursor self.SetCursor(wx.StockCursor(wx.CURSOR_PENCIL)) # bind some mouse events self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) self.Bind(wx.EVT_MOTION, self.OnMotion) def OnLeftDown(self, event): """left mouse button is pressed""" pt = event.GetPosition() # position tuple self.SetTitle('LeftMouse click at = ' + str(pt)) def OnRightDown(self, event): """right mouse button is pressed""" pt = event.GetPosition() self.SetTitle('RightMouse click at = ' + str(pt)) def OnMotion(self, event): """mouse in motion""" pt = event.GetPosition() self.SetTitle('Mouse in motion at = ' + str(pt)) app = wx.App(0) MyFrame(None).Show() app.MainLoop()
May 'the Google' be with you!
Applying different fonts to a text display ...
python Syntax (Toggle Plain Text)
# test wx.Font() and wx.FontDialog on a given text # wx.Font(pointSize, family, style, weight, underline=false, faceName="", # encoding=wx.FONTENCODING_DEFAULT) import wx class MyFrame(wx.Frame): def __init__(self, parent, title, data): wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(600, 400)) panel = wx.Panel(self, wx.ID_ANY) button = wx.Button(panel, wx.ID_ANY, label='Change Font', pos=(3, 3)) button.Bind(wx.EVT_BUTTON, self.changeFont) # family: wx.DEFAULT, wx.DECORATIVE, wx.ROMAN, wx.SCRIPT, # wx.SWISS, wx.MODERN # style: wx.NORMAL, wx.SLANT or wx.ITALIC # weight: wx.NORMAL, wx.LIGHT or wx.BOLD font = wx.Font(16, wx.SCRIPT, wx.NORMAL, wx.LIGHT) # use additional fonts this way ... #face = u'Comic Sans MS' #font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.NORMAL, False, face) self.text = wx.StaticText(panel, wx.ID_ANY, data, pos=(10,35)) self.text.SetFont(font) def changeFont(self, event): dialog = wx.FontDialog(None, wx.FontData()) if dialog.ShowModal() == wx.ID_OK: data = dialog.GetFontData() font = data.GetChosenFont() self.text.SetForegroundColour(data.GetColour()) self.text.SetFont(font) dialog.Destroy() data = """\ Al Gore: The Wild Years America's Most Popular Lawyers Career Opportunities for History Majors Different Ways to Spell "Bob" Ethiopian Tips on World Dominance Everything Men Know About Women Everything Women Know About Men Staple Your Way to Success The Amish Phone Book The Engineer's Guide to Fashion Ralph Nader's list of pleasures""" app = wx.App(0) # create instance of MyFrame and show MyFrame(None, "Text and Font", data).Show() # start the event loop app.MainLoop()
Last edited by vegaseat; Jul 10th, 2008 at 9:50 am. Reason: more detail added
May 'the Google' be with you!
You can use wxPython's ImageDialog to preview the image to be loaded. Also use a scrolled window to display oversized images ...
python Syntax (Toggle Plain Text)
# test the wx.lib.imagebrowser.ImageDialog() # and display the loaded image on a scrolled window import wx import os import wx.lib.imagebrowser class MyFrame(wx.Frame): def __init__(self, parent, mytitle): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=(600,400), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE) # create a srolled window to put the image on self.scrollw = wx.ScrolledWindow(self, wx.ID_ANY) self.scrollw.SetBackgroundColour('green') # set EnableScrolling(bool x_scrolling, bool y_scrolling) self.scrollw.EnableScrolling(True, True) # create the scroll bars, set max width and height max_width = 1000 max_height = 1000 # SetScrollbars(pixelsPerUnitX, pixelsPerUnitY, noUnitsX, noUnitsY) self.scrollw.SetScrollbars(20, 20, max_width/20, max_height/20) # create a statusbar at the bottom of the frame self.CreateStatusBar() # create the menubar at the top of the frame menubar = wx.MenuBar() # setting up the menu filemenu = wx.Menu() # alt/o is hotkey, "Open file" shows up in statusbar filemenu.Append(wx.ID_OPEN, "&Open","Open image file") filemenu.AppendSeparator() # alt/x is hotkey filemenu.Append(wx.ID_EXIT,"E&xit","Exit program") # add the filemenu to the menubar menubar.Append(filemenu,"&File") # add the finished menubar to the frame/window self.SetMenuBar(menubar) # bind event to an action self.Bind(wx.EVT_MENU, self.onExit, id=wx.ID_EXIT) self.Bind(wx.EVT_MENU, self.onOpen, id=wx.ID_OPEN) def onExit(self,event): """close the frame""" self.Close(True) def onOpen(self,event): """open an image file via wx.lib.imagebrowser.ImageDialog()""" dirname = '' dialog = wx.lib.imagebrowser.ImageDialog(self, dirname) if dialog.ShowModal() == wx.ID_OK: filename = dialog.GetFile() image = wx.Bitmap(filename) self.SetStatusText(filename) # bitmap upper left corner is in position (x, y) = (5, 5) wx.StaticBitmap(self.scrollw, wx.ID_ANY, image, pos=(5, 5), size=(image.GetWidth(), image.GetHeight())) dialog.Destroy() app = wx.App(0) # create MyFrame instance and show the frame MyFrame(None, "Test wx.lib.imagebrowser.ImageDialog()").Show() app.MainLoop()
May 'the Google' be with you!
Ever wanted to know how many named colours wxPython has? Here is a short demo code to find out ...
Might as well get used to the British spelling of colour!
I left some US spellings in there for you to find.
python Syntax (Toggle Plain Text)
# test the wx.Choice() widget and wx.lib.colourdb # wx.Choice(parent, id, pos, size, choices, style) # has no style options import wx import wx.lib.colourdb as colourdb class MyFrame(wx.Frame): def __init__(self, parent, mytitle, mysize): wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize) # create a panel to show the selected colour self.panel = wx.Panel(self, wx.ID_ANY, pos=(0,40), size=(250, 130)) # create a sorted colour list from the wx colour data base colourdb.updateColourDB() colour_list = sorted(colourdb.getColourList()) # create a choice widget self.choice = wx.Choice(self, wx.ID_ANY, choices=colour_list) # select item 0 (first item) in sorted colour list self.choice.SetSelection(0) # set the current frame color to the choice self.SetBackgroundColour(self.choice.GetStringSelection()) # bind the checkbox events to an action self.choice.Bind(wx.EVT_CHOICE, self.onChoice) def onChoice(self, event): bgcolour = self.choice.GetStringSelection() # change colour of the panel to the selected colour ... self.panel.SetBackgroundColour(bgcolour) self.panel.Refresh() # show the selected color in the frame title self.SetTitle(bgcolour.lower()) app = wx.App(0) # create a MyFrame instance and show MyFrame(None, 'Select a colour', (250, 170)).Show() app.MainLoop()
I left some US spellings in there for you to find.
Last edited by vegaseat; Jul 12th, 2008 at 5:06 pm. Reason: colour
May 'the Google' be with you!
The wx.RadioBox() widget is just a convenient way to group a bunch of radio buttons and give them a title. Radio buttons are used if you want only one of the group selected. Here is an example ...
python Syntax (Toggle Plain Text)
# test the wx.RadioBox() widget # wx.RadioBox(parent, id, label, pos, size, choices, style) # combines a wx.StaticBox() with wx.RadioButton() # only one radiobutton can be selected 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") self.options = ['now', 'later', 'much later', 'never'] # create an input widget self.radiobox = wx.RadioBox(self, wx.ID_ANY, "Select one option", pos=(10, 10), choices=self.options, style=wx.VERTICAL) # set radio button 1 as selected (first button is 0) self.radiobox.SetSelection(1) # bind mouse click to an action self.radiobox.Bind(wx.EVT_RADIOBOX, self.onAction) # create an output widget self.label = wx.StaticText(self, wx.ID_ANY, "" , pos=(10, 120)) # show present selection self.onAction(None) def onAction(self, event): """ some action code""" #index = self.radiobox.GetSelection() #s = "You selected option " + self.options[index] # better ... s = "You selected option " + self.radiobox.GetStringSelection() self.label.SetLabel(s) app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'testing wx.RadioBox()', (300, 200)).Show() app.MainLoop()
May 'the Google' be with you!
The wx.SpinCtrl() is a graphical way to enter integers. You can click on the up or down arrows to change the value, or use the keyboard to type the value directly, once the spinbox has the focus. Just run the code to see what it does ...
python Syntax (Toggle Plain Text)
# test the wx.SpinCtrl() widget # wx.SpinCtrl(parent, id, value, pos, size, style, min, max, initial) # used for integer number input # style = # wx.SP_ARROW_KEYS can use arrow keys to change the value # wx.SP_WRAP value wraps at the minimum and maximum. 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") # create a spinctrl widget for inteer input self.spin = wx.SpinCtrl( self, wx.ID_ANY, value="", pos=(10, 20), size=(80, 25), min=-100, max=1000, initial=98, style=wx.SP_ARROW_KEYS) # bind mouse click on arrows to an action self.spin.Bind(wx.EVT_SPINCTRL, self.onAction) # you can edit the value directly self.spin.Bind(wx.EVT_TEXT, self.onAction) # create an output widget s1 = "click on arrows to change the spinbox value \n" s2 = "or type the integer value directly" self.label = wx.StaticText(self, wx.ID_ANY, s1+s2, pos=(10, 60)) def onAction(self, event): """ some action code""" val = self.spin.GetValue() f = str(round(val * 9.0/5 + 32, 2)) c = str(round((val - 32)*5/9.0, 2)) v = str(val) s1 = v + " degree Fahrenheit is " + c + " degree Celcius \n" s2 = v + " degree Celcius is " + f + " degree Fahrenheit" self.label.SetLabel(s1 + s2) app = wx.App(0) # create a MyFrame instance and show the frame MyFrame(None, 'testing the wx.SpinCtrl()', (300, 150)).Show() app.MainLoop()
Last edited by vegaseat; Jul 13th, 2008 at 3:21 pm.
May 'the Google' be with you!
You can input a date the graphical way, let's call it the wxPythonian way, with a simple mouse point and click:
python Syntax (Toggle Plain Text)
# explore the wx.calendar.CalendarCtrl() control # allows for point and click date input import wx import wx.calendar as cal class MyCalendar(wx.Dialog): """create a simple dialog window with a calendar display""" def __init__(self, parent, mytitle): wx.Dialog.__init__(self, parent, wx.ID_ANY, mytitle) # use a box sizer to position controls vertically vbox = wx.BoxSizer(wx.VERTICAL) # wx.DateTime_Now() sets calendar to current date self.calendar = cal.CalendarCtrl(self, wx.ID_ANY, wx.DateTime_Now()) vbox.Add(self.calendar, 0, wx.EXPAND|wx.ALL, border=20) # click on day self.calendar.Bind(cal.EVT_CALENDAR_DAY, self.onCalSelected) # change month self.calendar.Bind(cal.EVT_CALENDAR_MONTH, self.onCalSelected) # change year self.calendar.Bind(cal.EVT_CALENDAR_YEAR, self.onCalSelected) self.label = wx.StaticText(self, wx.ID_ANY, 'click on a day') vbox.Add(self.label, 0, wx.EXPAND|wx.ALL, border=20) button = wx.Button(self, wx.ID_ANY, 'Exit') vbox.Add(button, 0, wx.ALL|wx.ALIGN_CENTER, border=20) self.Bind(wx.EVT_BUTTON, self.onQuit, button) self.SetSizerAndFit(vbox) self.Show(True) self.Centre() def onCalSelected(self, event): #date = event.GetDate() date = self.calendar.GetDate() day = date.GetDay() # for some strange reason month starts with zero month = date.GetMonth() + 1 # year is yyyy format year = date.GetYear() s1 = "%02d/%02d/%d \n" % (month, day, year) # or just take a slice of the first 8 characters to show mm/dd/yy s2 = str(date)[0:8] self.label.SetLabel(s1 + s2) def onQuit(self, event): self.Destroy() app = wx.App() MyCalendar(None, 'wx.calendar.CalendarCtrl()') app.MainLoop()
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 |
alarm ansi anydbm app assignment backend beginner binary bluetooth character cipher cmd coordinates customdialog cx-freeze data decimals development directory dynamic exe feet file float format function generator getvalue gnu graphics halp handling heads homework http ideas input ip itunes java keycontrol leftmouse line linux list lists loop maintain maze millimeter module mouse number numbers output parsing path pointer prime programming progressbar push py2exe pygame pymailer python queue random recursion recursive schedule screensaverloopinactive script slicenotation sqlite ssh statistics string strings sudokusolver text thread time tlapse tuple ubuntu unicode url urllib urllib2 variable ventrilo vigenere web webservice wikipedia write wxpython xlib xlwt






