| | |
Starting Python
![]() |
Thanks BearofNH, very nice contribution on generators. If you work with generators, you will find module itertools very handy. Here is an example ...
python Syntax (Toggle Plain Text)
# use itertools.islice(iterable, [start,] stop [, step]) # to get selected results of a generator function ... from itertools import islice def fibo_generator(): """ a generator for Fibonacci numbers, goes to next number in series on each call """ current, previous = 0, 1 while True: yield current # use a tuple swap current, previous = previous, current + previous print "show Fibonacci number for n = 10:" for k in islice(fibo_generator(), 10, 11): print k, print; print print "show Fibonacci series for n = 7 to 10:" for k in islice(fibo_generator(), 7, 11): print k,
May 'the Google' be with you!
This shows you how you can use a background image in your Tkinter GUI programs. I used PIL to be able to load image formats other than the 'Tinter only .gif' ...
To copy and paste this code into your editor without the line numbers, click on the 'Toggle Plain Text' area. Now you can highlight and copy.
python Syntax (Toggle Plain Text)
# use a Tkinter label as a panel for a background image # note that Tkinter only reads .gif and .ppm images # use the Python Image Library (PIL) for other image formats # free from [url]http://www.pythonware.com/products/pil/index.htm[/url] # give Tkinter a namespace to avoid conflicts with PIL # (they both have a class named Image) import Tkinter as tk from PIL import Image, ImageTk root = tk.Tk() root.title('background image') # pick an image file you have .bmp .jpg .gif. .png # load the file and covert it to a Tkinter image object imageFile = "Flowers.jpg" image1 = ImageTk.PhotoImage(Image.open(imageFile)) # get the image size w = image1.width() h = image1.height() # position coordinates of root 'upper left corner' x = 0 y = 0 # make the root window the size of the image root.geometry("%dx%d+%d+%d" % (w, h, x, y)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=image1) panel1.pack(side='top', fill='both', expand='yes') # put a button on the image panel to test it button2 = tk.Button(panel1, text='button2') button2.pack(side='top') # save the panel's image from 'garbage collection' panel1.image = image1 # start the event loop root.mainloop()
Last edited by vegaseat; May 27th, 2007 at 1:02 pm. Reason: (Toggle Plain Text) help
May 'the Google' be with you!
Thanks for the itertools tip, vegaseat. And the much tighter generator code.
Almost makes you wonder if Python could be enhanced to allow subscript/slice syntax to "index" generators, as in:
Of course there would be a number of semantic issues to work out, such as stability of results.
Almost makes you wonder if Python could be enhanced to allow subscript/slice syntax to "index" generators, as in:
>>>g = fibo_generator()
>>>print g[0:10]
0 1 1 2 3 5 8 13 21 34 55 If you want to determine the size of a file folder and it's subfolders, use this handy little utility ...
python Syntax (Toggle Plain Text)
# determine size of a given folder in MBytes import os # pick a folder you have ... folder = 'D:\\zz1' folder_size = 0 for (path, dirs, files) in os.walk(folder): for file in files: filename = os.path.join(path, file) folder_size += os.path.getsize(filename) print "Folder = %0.1f MB" % (folder_size/(1024*1024.0))
May 'the Google' be with you!
For those of you, who absolutely have to clear the console screen, you can use:
This of course leaves the cursor at the bottom of the screen. If you don't like that, this will do better:
python Syntax (Toggle Plain Text)
print '\n'*35
python Syntax (Toggle Plain Text)
# works on Windows or Linux, also Vista import os os.system(['clear','cls'][os.name == 'nt'])
Should you find Irony, you can keep her!
For those of you who like visual frame builders/designers for the wxPython toolkit, wxGlade has been much improved lately. You can down load it free from:
http://wxglade.sourceforge.net/
It also comes integrated into Stani's Python Editior (SPE), which is still available from:
http://www.tradebit.com/filedetail.php/839343
Downloads as spe-0.8.3c.zip, and will work with Python 2.3 - 2.5. Simply extract the '_spe' directory into your Python 'lib' folder. You can then run 'spe.pyw' from there. Again, you need the wxPython GUI toolkit installed first for SPE and wxGlade to work!
wxGlade takes one moment to get used to, there is one short tutorial.
http://wxglade.sourceforge.net/
It also comes integrated into Stani's Python Editior (SPE), which is still available from:
http://www.tradebit.com/filedetail.php/839343
Downloads as spe-0.8.3c.zip, and will work with Python 2.3 - 2.5. Simply extract the '_spe' directory into your Python 'lib' folder. You can then run 'spe.pyw' from there. Again, you need the wxPython GUI toolkit installed first for SPE and wxGlade to work!
wxGlade takes one moment to get used to, there is one short tutorial.
Last edited by bumsfeld; Jul 7th, 2007 at 2:37 pm.
Should you find Irony, you can keep her!
An example how to set up a wxPython GUI toolkit application with Boa Constructor, an IDE with a built in visual frame builder/designer along the line of the Delphi RAD tool.
These are the instructions how work with a wx.ListBox:
Here is the resulting code ...
These are the instructions how work with a wx.ListBox:
•
•
•
•
Download and install boa-constructor-0.6.1.bin.setup.exe from:
http://sourceforge.net/project/downl...p.exe&74856058
Then run Boa.exe
1) Start with 'File'/'New'/'wx.Frame'
(this will allow you to create just one source file).
2) Click on the 'frame designer' button (square box with up arrow),
the frame shows and you can drag it more to the center of the screen,
away from the Inspector information.
You can drag the edges of the frame to change the size.
Size and position details show in the 'Constr' page of the Inspector.
3) Open the Inspector 'Props' page, move to BackGroundColour and
click on (wx.Colour) then on the '...' button.
Pick a background color from the colour palette (eg. green),
the frame will fill with the selected colour.
4) Click on the 'Buttons' tab and select a wx.Button.
Drop it on the frame somewhere near the top.
Drop two more wx.buttons near the frame bottom.
We will drag them to the correct position later.
5) Click on the 'List Controls' tab and select a wx.ListBox.
Drop it on the middle of the frame.
You can stretch the ListBox to the size you want, and
drag it to right position on the frame.
6) Now position the buttons where you want them.
Drag button1 to top of the list, button2 and button3
just below the list.
7) Let's label the buttons ...
click on button1 and in the Inspector 'Constr' page look
for Label and type in 'Load List'.
Similarly label button2 'Sort List' and button3 'Clear List'.
8) Leave the Inspector by clicking on the v shaped checkmark icon
(Post the session).
You can now take a look at the the source code Boa has created
so far. To make this an executable module, put the cursor at
the end of the code, and click an 'Edit'/'Add Module Runner'. This
will add the necessary code to the end of the file. It will run the code
as a wx.PySimpleApp().
9) It's time we save our efforts via File/Save or clicking
the filesave icon. You may want to create a new folder and
save the program as 'wxListBoxTest1.py'
10) After you have saved the program code, you can test drive it
by clicking on the blue triangle icon (Run module). Admire
it and then exit your program you have just created.
11) Now we have to bind the buttons to a button click event.
Go back to the Frame Designer (up arrow in a square block icon).
Select the 'Load List" button by clicking on it. In the Inspector's
'Evts' page double click on 'ButtonEvent' and then double click on the
resulting 'wx.EVT_BUTTON'. There will be an entry below that
telling you that the button click is bound to a function called
'OnButton1Button'.
12) Leave the Inspector by clicking on the v shaped checkmark icon,
and look a the changed source code, there will be a
button1.Bind() statement and the function definition named
'OnButton1Button()'.
13) Return to the Frame Designer and do the same operations for
button2 (Sort) and button3 (Clear).
Click on the ListBox and move to the Inspector's 'Evts' page.
Double click on 'ListBoxEvent' and then on 'wx.EVT_LISTBOX'.
This will bind to a function called 'OnListBox1Listbox'.
14) Your Windows frame is now designed, so leave the Inspector
(v shaped checkmark icon). Look over the generated code.
The various generated function have a place holder statement
'event.Skip()'. You need to replace this statement with the
meat of your program.
Add strings to the ListBox with:
self.listBox1.Append("some string")
Get the selected string from the LisBox with:
selected = self.listBox1.GetStringSelection()
Clear the ListBox strings with
self.listBox1.Clear()
Sorting is done by transferring the ListBox strings to
regular Python list container with:
name_list = self.listBox1.GetItems()
Then sort the list and reload the cleared ListBox with:
self.listBox1.Set(name_list)
15) Save any code modifications before you run the program!
python Syntax (Toggle Plain Text)
#Boa:Frame:Frame1 import wx def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1BUTTON2, wxID_FRAME1BUTTON3, wxID_FRAME1LISTBOX1, ] = [wx.NewId() for _init_ctrls in range(5)] class Frame1(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, pos=wx.Point(355, 138), size=wx.Size(255, 385), style=wx.DEFAULT_FRAME_STYLE, title='Frame1') self.SetClientSize(wx.Size(247, 345)) self.SetBackgroundColour(wx.Colour(0, 128, 0)) self.button1 = wx.Button(id=wxID_FRAME1BUTTON1, label='Load List', name='button1', parent=self, pos=wx.Point(16, 16), size=wx.Size(87, 28), style=0) self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button, id=wxID_FRAME1BUTTON1) self.button2 = wx.Button(id=wxID_FRAME1BUTTON2, label='Sort List', name='button2', parent=self, pos=wx.Point(16, 296), size=wx.Size(87, 28), style=0) self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button, id=wxID_FRAME1BUTTON2) self.button3 = wx.Button(id=wxID_FRAME1BUTTON3, label='Clear List', name='button3', parent=self, pos=wx.Point(136, 296), size=wx.Size(87, 28), style=0) self.button3.Bind(wx.EVT_BUTTON, self.OnButton3Button, id=wxID_FRAME1BUTTON3) self.listBox1 = wx.ListBox(choices=[], id=wxID_FRAME1LISTBOX1, name='listBox1', parent=self, pos=wx.Point(16, 64), size=wx.Size(208, 216), style=0) self.listBox1.Bind(wx.EVT_LISTBOX, self.OnListBox1Listbox, id=wxID_FRAME1LISTBOX1) def __init__(self, parent): self._init_ctrls(parent) def OnButton1Button(self, event): ''' click button to load the ListBox with names ''' self.listBox1.Append("Andreas") self.listBox1.Append("Erich") self.listBox1.Append("Udo") self.listBox1.Append("Jens") self.listBox1.Append("Bjorn") self.listBox1.Append("Heidrun") self.listBox1.Append("Ulla") self.listBox1.Append("Volger") self.listBox1.Append("Helmut") self.listBox1.Append("Freja") self.listBox1.Append("Nathan") self.listBox1.Append("Jerry") self.listBox1.Append("Lamar") self.SetTitle("Select a name ...") #event.Skip() def OnButton2Button(self, event): ''' put the ListBox items into a Python list, sort and reload ''' # GetItems() new in wxPython2.8 name_list = self.listBox1.GetItems() name_list.sort() # Set() clears and reloads self.listBox1.Set(name_list) #event.Skip() def OnButton3Button(self, event): ''' click button to clear the ListBox items ''' self.listBox1.Clear() #event.Skip() def OnListBox1Listbox(self, event): ''' click ListBox item and display the selected string in the frame title ''' selName = self.listBox1.GetStringSelection() self.SetTitle(selName) #event.Skip() # added by BOA via Edit/Add Module Runner if __name__ == '__main__': app = wx.PySimpleApp() frame = create(None) frame.Show() app.MainLoop()
Last edited by vegaseat; Jul 9th, 2007 at 3:16 am. Reason: spelling
May 'the Google' be with you!
If you are interested in 3D graphics, then you can use the free visual module from Visual Python (VPython) at: http://vpython.org/
Here is a nice example of a bouncing ball between two walls. Best of all, you can press the right mouse button to drag/rotate the view in space. An interesting module for any science oriented person ...
Here is a nice example of a bouncing ball between two walls. Best of all, you can press the right mouse button to drag/rotate the view in space. An interesting module for any science oriented person ...
python Syntax (Toggle Plain Text)
# bouncing a ball of the walls using VPython # press the right mouse button to drag/rotate the whole thing # experiments with visual Python from vpython.org import visual as vs # create a red ball ball_radius = 0.7 ball = vs.sphere(pos=(-5, 0, 0), radius=ball_radius, color=vs.color.red) # create 2 green opposing walls wall_right = vs.box(pos=(6, 0, 0), size=(0.2, 4, 4), color=vs.color.green) wall_left = vs.box(pos=(-6, 0, 0), size=(0.2, 4, 4), color=vs.color.green) # size movement of the ball dt = 0.05 ball.velocity = vs.vector(2,0,0) # loop it to create the animation while True: # time the moving ball, higher value gives faster speed vs.rate(50) ball.pos = ball.pos + ball.velocity * dt # the ball needs to bounce as it touches the wall if ball.x > wall_right.x - ball_radius: ball.velocity.x = -ball.velocity.x if ball.x < wall_left.x + ball_radius: ball.velocity.x = -ball.velocity.x
May 'the Google' be with you!
If you work with Python dictionary objects, you can make them persistent to file using the module shelve ...
Now the dictionary you worked with has been made persistent in file 'Slogan.SLV' and you can open this file and work with the dictionary ...
python Syntax (Toggle Plain Text)
# ShelveData1.py # create and initialize a class/structure and save the data to # a shelve byte stream file that behaves like a dictionary import shelve # a Python class to mimic a C structure or Pascal record class Person(object): """__init__() functions as the class constructor""" def __init__(self, name=None, sex=None, slogan=None): self.name = name self.sex = sex self.slogan = slogan def __getattr__(self, attr): """allow for additional (derived) attributes""" if attr == 'firstname': # assumes name = "first last", slice to the first space return self.name[0:self.name.find(" ")] else: raise AttributeError # initialize and load the class (structure) like this ... emma = Person("Emma Porke", "female", "Vote for Bush and Dick") jack = Person("Jack Schidd", "male", "Never give a schidd!") # ... or like this (looks more like C) ... arnie = Person() arnie.name = "Arnold Negerschwarz" arnie.sex = "often" arnie.slogan = "I know how to spell nukilar!" # this will open or create a shelve file called 'Slogan.SLV' dbs1 = shelve.open('Slogan.SLV') # note that a shelve file behaves like a {obj.name:object} dictionary for obj in (arnie, emma, jack): # creating the dictionary will automatically save the data to file # for each pair key is the objects name and the value is the object dbs1[obj.name] = obj # let's add one more ... frank = Person("Frank Palermo", "male", "An innuendo is a suppository") # again, this will automatically save the data to file dbs1[frank.name] = frank print "Saved all data to shelve file 'Slogan.SLV'" # done adding any additional data, close the file (optional, but a good habit) dbs1.close()
python Syntax (Toggle Plain Text)
# ShelveData2.py # load the shelve file 'Slogan.SLV' that was created in ShelveData1.py import shelve # you need the same class you used for writing the shelve data, but # you can add additional attributes derived from the initial attributes class Person(object): """__init__() functions as the class constructor""" def __init__(self, name=None, sex=None, slogan=None): self.name = name self.sex = sex self.slogan = slogan def __getattr__(self, attr): """allow for additional (derived) attributes""" if attr == 'firstname': # assumes name = "first last", slice to the first space return self.name[0:self.name.find(" ")] elif attr == 'lastname': # assumes name = "first last", slice from the first space return self.name[self.name.find(" ")+1:] elif attr == 'title': # automagically creates a title for the person if self.sex == 'male': return "Mister" elif self.sex == 'female': return "Miss" else: return "Rep." else: raise AttributeError # open the previously created shelve data file dbs2 = shelve.open('Slogan.SLV') # test it, remember that shelve data work like a dictionary # these are the keys (the objects names) print dbs2.keys() # ['Jack Schidd', 'Arnold Negerschwarz', 'Emma Porke'] # to access data you can use print "Emma's slogan:", dbs2['Emma Porke'].slogan # or simply reestablish objects emma, jack, arnie and frank emma = dbs2['Emma Porke'] jack = dbs2['Jack Schidd'] arnie = dbs2['Arnold Negerschwarz'] frank = dbs2['Frank Palermo'] print "Just objects emma and jack:" print '%s says "%s"' % (emma.name, emma.slogan) print '%s says "%s"' % (jack.name, jack.slogan) # show it the Pythonian way (good for large person lists) ... print "The whole list of names (the Pythonian way):" personList = [emma, jack, arnie, frank] for pers in personList: #print '%s says "%s"' % (getattr(pers, "name"), getattr(pers, "slogan")) # simpler ... print '%s says "%s"' % (pers.name, pers.slogan) # this works without establishing objects like emma, jack and arnie ... # the order will be the dictionary's key order print "The whole list (the generic way):" for key in dbs2.keys(): exec("x = dbs2[key]") print '%s %s says "%s"' % (x.title, x.lastname, x.slogan) # or you can search selected data ... print "A search of selected data:" for key in dbs2.keys(): exec("x = dbs2[key]") if x.firstname == "Arnold": print '%s says "%s"' % (x.firstname, x.slogan) if x.lastname == "Porke": print '%s %s says "%s"' % (x.title, x.name, x.slogan) # any changes you make to the dictionary will be # automatically saved to file, let's try this jack.slogan = "No more schidd!" # test it ... print "Modified data:" personList = [emma, jack, arnie, frank] for pers in personList: print '%s says "%s"' % (pers.firstname, pers.slogan)
Last edited by vegaseat; Dec 14th, 2007 at 2:08 am. Reason: comments
May 'the Google' be with you!
![]() |
Similar Threads
- CGPA calculator (Python)
- Beginning: Starting Python (Python)
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: wxpython GUI issue with database
- Next Thread: error in numpy
| Thread Tools | Search this Thread |
access anti api beginner binary blogger blogging bug c# c++ code combo crash csv curved cx-freeze daniweb data database developers development dictionary digital dropdownlist dynamic editcodesnippet event exam examples excel fanniemay file format function game gdata google gui http image images input introduction ip itunes java joomla kernel key library linux list lists maze method microsoft module mouse mvcmodel2 net news opensource php problem professor program programming projects py2exe pygame pyglet python random reuse rss script security serial servlet shutdown source sqlite string tagging test text tutorial ubuntu unicode urllib urllib2 variable ventrilo virus vista visualbasic6 web windows wxpython xml







