Starting Python

Reply

Join Date: Oct 2004
Posts: 3,857
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #101
May 19th, 2007
Thanks BearofNH, very nice contribution on generators. If you work with generators, you will find module itertools very handy. Here is an example ...
  1. # use itertools.islice(iterable, [start,] stop [, step])
  2. # to get selected results of a generator function ...
  3.  
  4. from itertools import islice
  5.  
  6. def fibo_generator():
  7. """
  8. a generator for Fibonacci numbers, goes
  9. to next number in series on each call
  10. """
  11. current, previous = 0, 1
  12. while True:
  13. yield current
  14. # use a tuple swap
  15. current, previous = previous, current + previous
  16.  
  17. print "show Fibonacci number for n = 10:"
  18. for k in islice(fibo_generator(), 10, 11):
  19. print k,
  20.  
  21. print; print
  22.  
  23. print "show Fibonacci series for n = 7 to 10:"
  24. for k in islice(fibo_generator(), 7, 11):
  25. print k,
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,857
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #102
May 27th, 2007
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' ...
  1. # use a Tkinter label as a panel for a background image
  2. # note that Tkinter only reads .gif and .ppm images
  3. # use the Python Image Library (PIL) for other image formats
  4. # free from [url]http://www.pythonware.com/products/pil/index.htm[/url]
  5. # give Tkinter a namespace to avoid conflicts with PIL
  6. # (they both have a class named Image)
  7.  
  8. import Tkinter as tk
  9. from PIL import Image, ImageTk
  10.  
  11. root = tk.Tk()
  12. root.title('background image')
  13.  
  14. # pick an image file you have .bmp .jpg .gif. .png
  15. # load the file and covert it to a Tkinter image object
  16. imageFile = "Flowers.jpg"
  17. image1 = ImageTk.PhotoImage(Image.open(imageFile))
  18.  
  19. # get the image size
  20. w = image1.width()
  21. h = image1.height()
  22.  
  23. # position coordinates of root 'upper left corner'
  24. x = 0
  25. y = 0
  26.  
  27. # make the root window the size of the image
  28. root.geometry("%dx%d+%d+%d" % (w, h, x, y))
  29.  
  30. # root has no image argument, so use a label as a panel
  31. panel1 = tk.Label(root, image=image1)
  32. panel1.pack(side='top', fill='both', expand='yes')
  33.  
  34. # put a button on the image panel to test it
  35. button2 = tk.Button(panel1, text='button2')
  36. button2.pack(side='top')
  37.  
  38. # save the panel's image from 'garbage collection'
  39. panel1.image = image1
  40.  
  41. # start the event loop
  42. root.mainloop()
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.
Last edited by vegaseat; May 27th, 2007 at 1:02 pm. Reason: (Toggle Plain Text) help
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: May 2007
Posts: 311
Reputation: BearofNH is on a distinguished road 
Solved Threads: 40
BearofNH's Avatar
BearofNH BearofNH is offline Offline
Posting Whiz

Re: Starting Python

 
0
  #103
May 29th, 2007
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:
>>>g = fibo_generator()
>>>print g[0:10]
0 1 1 2 3 5 8 13 21 34 55
Of course there would be a number of semantic issues to work out, such as stability of results.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,857
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #104
Jun 19th, 2007
If you want to determine the size of a file folder and it's subfolders, use this handy little utility ...
  1. # determine size of a given folder in MBytes
  2.  
  3. import os
  4.  
  5. # pick a folder you have ...
  6. folder = 'D:\\zz1'
  7. folder_size = 0
  8. for (path, dirs, files) in os.walk(folder):
  9. for file in files:
  10. filename = os.path.join(path, file)
  11. folder_size += os.path.getsize(filename)
  12.  
  13. print "Folder = %0.1f MB" % (folder_size/(1024*1024.0))
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,205
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 130
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #105
Jul 4th, 2007
For those of you, who absolutely have to clear the console screen, you can use:
  1. print '\n'*35
This of course leaves the cursor at the bottom of the screen. If you don't like that, this will do better:
  1. # works on Windows or Linux, also Vista
  2. import os
  3. os.system(['clear','cls'][os.name == 'nt'])
Should you find Irony, you can keep her!
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,205
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 130
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #106
Jul 7th, 2007
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.
Last edited by bumsfeld; Jul 7th, 2007 at 2:37 pm.
Should you find Irony, you can keep her!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,857
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #107
Jul 7th, 2007
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:
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!
Here is the resulting code ...
  1. #Boa:Frame:Frame1
  2.  
  3. import wx
  4.  
  5. def create(parent):
  6. return Frame1(parent)
  7.  
  8. [wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1BUTTON2, wxID_FRAME1BUTTON3,
  9. wxID_FRAME1LISTBOX1,
  10. ] = [wx.NewId() for _init_ctrls in range(5)]
  11.  
  12. class Frame1(wx.Frame):
  13. def _init_ctrls(self, prnt):
  14. # generated method, don't edit
  15. wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
  16. pos=wx.Point(355, 138), size=wx.Size(255, 385),
  17. style=wx.DEFAULT_FRAME_STYLE, title='Frame1')
  18. self.SetClientSize(wx.Size(247, 345))
  19. self.SetBackgroundColour(wx.Colour(0, 128, 0))
  20.  
  21. self.button1 = wx.Button(id=wxID_FRAME1BUTTON1, label='Load List',
  22. name='button1', parent=self, pos=wx.Point(16, 16),
  23. size=wx.Size(87, 28), style=0)
  24. self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,
  25. id=wxID_FRAME1BUTTON1)
  26.  
  27. self.button2 = wx.Button(id=wxID_FRAME1BUTTON2, label='Sort List',
  28. name='button2', parent=self, pos=wx.Point(16, 296),
  29. size=wx.Size(87, 28), style=0)
  30. self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
  31. id=wxID_FRAME1BUTTON2)
  32.  
  33. self.button3 = wx.Button(id=wxID_FRAME1BUTTON3, label='Clear List',
  34. name='button3', parent=self, pos=wx.Point(136, 296),
  35. size=wx.Size(87, 28), style=0)
  36. self.button3.Bind(wx.EVT_BUTTON, self.OnButton3Button,
  37. id=wxID_FRAME1BUTTON3)
  38.  
  39. self.listBox1 = wx.ListBox(choices=[], id=wxID_FRAME1LISTBOX1,
  40. name='listBox1', parent=self, pos=wx.Point(16, 64),
  41. size=wx.Size(208, 216), style=0)
  42. self.listBox1.Bind(wx.EVT_LISTBOX, self.OnListBox1Listbox,
  43. id=wxID_FRAME1LISTBOX1)
  44.  
  45. def __init__(self, parent):
  46. self._init_ctrls(parent)
  47.  
  48. def OnButton1Button(self, event):
  49. '''
  50. click button to load the ListBox with names
  51. '''
  52. self.listBox1.Append("Andreas")
  53. self.listBox1.Append("Erich")
  54. self.listBox1.Append("Udo")
  55. self.listBox1.Append("Jens")
  56. self.listBox1.Append("Bjorn")
  57. self.listBox1.Append("Heidrun")
  58. self.listBox1.Append("Ulla")
  59. self.listBox1.Append("Volger")
  60. self.listBox1.Append("Helmut")
  61. self.listBox1.Append("Freja")
  62. self.listBox1.Append("Nathan")
  63. self.listBox1.Append("Jerry")
  64. self.listBox1.Append("Lamar")
  65. self.SetTitle("Select a name ...")
  66. #event.Skip()
  67.  
  68. def OnButton2Button(self, event):
  69. '''
  70. put the ListBox items into a Python list, sort and reload
  71. '''
  72. # GetItems() new in wxPython2.8
  73. name_list = self.listBox1.GetItems()
  74. name_list.sort()
  75. # Set() clears and reloads
  76. self.listBox1.Set(name_list)
  77. #event.Skip()
  78.  
  79. def OnButton3Button(self, event):
  80. '''
  81. click button to clear the ListBox items
  82. '''
  83. self.listBox1.Clear()
  84. #event.Skip()
  85.  
  86. def OnListBox1Listbox(self, event):
  87. '''
  88. click ListBox item and display the selected string in the frame title
  89. '''
  90. selName = self.listBox1.GetStringSelection()
  91. self.SetTitle(selName)
  92. #event.Skip()
  93.  
  94.  
  95. # added by BOA via Edit/Add Module Runner
  96. if __name__ == '__main__':
  97. app = wx.PySimpleApp()
  98. frame = create(None)
  99. frame.Show()
  100. app.MainLoop()
Last edited by vegaseat; Jul 9th, 2007 at 3:16 am. Reason: spelling
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Aug 2007
Posts: 8
Reputation: laseredd is an unknown quantity at this point 
Solved Threads: 0
laseredd laseredd is offline Offline
Newbie Poster

Re: Starting Python

 
0
  #108
Aug 24th, 2007
This doesn't matter too much, but in the code examples you wrote "Monte Python". I'm pretty sure it's spelt "Monty Python".

Editor's note: Thanks a lot! In this case it does matter, so I corrected this late night mistake!
Last edited by vegaseat; Aug 24th, 2007 at 3:55 pm. Reason: thanks
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,857
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #109
Sep 20th, 2007
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 ...
  1. # bouncing a ball of the walls using VPython
  2. # press the right mouse button to drag/rotate the whole thing
  3. # experiments with visual Python from vpython.org
  4.  
  5. import visual as vs
  6.  
  7. # create a red ball
  8. ball_radius = 0.7
  9. ball = vs.sphere(pos=(-5, 0, 0), radius=ball_radius, color=vs.color.red)
  10. # create 2 green opposing walls
  11. wall_right = vs.box(pos=(6, 0, 0), size=(0.2, 4, 4), color=vs.color.green)
  12. wall_left = vs.box(pos=(-6, 0, 0), size=(0.2, 4, 4), color=vs.color.green)
  13.  
  14. # size movement of the ball
  15. dt = 0.05
  16. ball.velocity = vs.vector(2,0,0)
  17.  
  18. # loop it to create the animation
  19. while True:
  20. # time the moving ball, higher value gives faster speed
  21. vs.rate(50)
  22. ball.pos = ball.pos + ball.velocity * dt
  23. # the ball needs to bounce as it touches the wall
  24. if ball.x > wall_right.x - ball_radius:
  25. ball.velocity.x = -ball.velocity.x
  26. if ball.x < wall_left.x + ball_radius:
  27. ball.velocity.x = -ball.velocity.x
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,857
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #110
Dec 14th, 2007
If you work with Python dictionary objects, you can make them persistent to file using the module shelve ...
  1. # ShelveData1.py
  2. # create and initialize a class/structure and save the data to
  3. # a shelve byte stream file that behaves like a dictionary
  4.  
  5. import shelve
  6.  
  7. # a Python class to mimic a C structure or Pascal record
  8. class Person(object):
  9. """__init__() functions as the class constructor"""
  10. def __init__(self, name=None, sex=None, slogan=None):
  11. self.name = name
  12. self.sex = sex
  13. self.slogan = slogan
  14.  
  15. def __getattr__(self, attr):
  16. """allow for additional (derived) attributes"""
  17. if attr == 'firstname':
  18. # assumes name = "first last", slice to the first space
  19. return self.name[0:self.name.find(" ")]
  20. else:
  21. raise AttributeError
  22.  
  23.  
  24. # initialize and load the class (structure) like this ...
  25. emma = Person("Emma Porke", "female", "Vote for Bush and Dick")
  26. jack = Person("Jack Schidd", "male", "Never give a schidd!")
  27.  
  28. # ... or like this (looks more like C) ...
  29. arnie = Person()
  30. arnie.name = "Arnold Negerschwarz"
  31. arnie.sex = "often"
  32. arnie.slogan = "I know how to spell nukilar!"
  33.  
  34. # this will open or create a shelve file called 'Slogan.SLV'
  35. dbs1 = shelve.open('Slogan.SLV')
  36.  
  37. # note that a shelve file behaves like a {obj.name:object} dictionary
  38. for obj in (arnie, emma, jack):
  39. # creating the dictionary will automatically save the data to file
  40. # for each pair key is the objects name and the value is the object
  41. dbs1[obj.name] = obj
  42.  
  43. # let's add one more ...
  44. frank = Person("Frank Palermo", "male", "An innuendo is a suppository")
  45. # again, this will automatically save the data to file
  46. dbs1[frank.name] = frank
  47.  
  48. print "Saved all data to shelve file 'Slogan.SLV'"
  49.  
  50. # done adding any additional data, close the file (optional, but a good habit)
  51. dbs1.close()
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 ...
  1. # ShelveData2.py
  2. # load the shelve file 'Slogan.SLV' that was created in ShelveData1.py
  3.  
  4. import shelve
  5.  
  6. # you need the same class you used for writing the shelve data, but
  7. # you can add additional attributes derived from the initial attributes
  8. class Person(object):
  9. """__init__() functions as the class constructor"""
  10. def __init__(self, name=None, sex=None, slogan=None):
  11. self.name = name
  12. self.sex = sex
  13. self.slogan = slogan
  14.  
  15. def __getattr__(self, attr):
  16. """allow for additional (derived) attributes"""
  17. if attr == 'firstname':
  18. # assumes name = "first last", slice to the first space
  19. return self.name[0:self.name.find(" ")]
  20. elif attr == 'lastname':
  21. # assumes name = "first last", slice from the first space
  22. return self.name[self.name.find(" ")+1:]
  23. elif attr == 'title':
  24. # automagically creates a title for the person
  25. if self.sex == 'male':
  26. return "Mister"
  27. elif self.sex == 'female':
  28. return "Miss"
  29. else:
  30. return "Rep."
  31. else:
  32. raise AttributeError
  33.  
  34.  
  35. # open the previously created shelve data file
  36. dbs2 = shelve.open('Slogan.SLV')
  37.  
  38. # test it, remember that shelve data work like a dictionary
  39. # these are the keys (the objects names)
  40. print dbs2.keys() # ['Jack Schidd', 'Arnold Negerschwarz', 'Emma Porke']
  41.  
  42. # to access data you can use
  43. print "Emma's slogan:", dbs2['Emma Porke'].slogan
  44.  
  45. # or simply reestablish objects emma, jack, arnie and frank
  46. emma = dbs2['Emma Porke']
  47. jack = dbs2['Jack Schidd']
  48. arnie = dbs2['Arnold Negerschwarz']
  49. frank = dbs2['Frank Palermo']
  50.  
  51. print
  52.  
  53. print "Just objects emma and jack:"
  54. print '%s says "%s"' % (emma.name, emma.slogan)
  55. print '%s says "%s"' % (jack.name, jack.slogan)
  56.  
  57. print
  58.  
  59. # show it the Pythonian way (good for large person lists) ...
  60. print "The whole list of names (the Pythonian way):"
  61. personList = [emma, jack, arnie, frank]
  62. for pers in personList:
  63. #print '%s says "%s"' % (getattr(pers, "name"), getattr(pers, "slogan"))
  64. # simpler ...
  65. print '%s says "%s"' % (pers.name, pers.slogan)
  66.  
  67. print
  68.  
  69. # this works without establishing objects like emma, jack and arnie ...
  70. # the order will be the dictionary's key order
  71. print "The whole list (the generic way):"
  72. for key in dbs2.keys():
  73. exec("x = dbs2[key]")
  74. print '%s %s says "%s"' % (x.title, x.lastname, x.slogan)
  75.  
  76. print
  77.  
  78. # or you can search selected data ...
  79. print "A search of selected data:"
  80. for key in dbs2.keys():
  81. exec("x = dbs2[key]")
  82. if x.firstname == "Arnold":
  83. print '%s says "%s"' % (x.firstname, x.slogan)
  84. if x.lastname == "Porke":
  85. print '%s %s says "%s"' % (x.title, x.name, x.slogan)
  86.  
  87. # any changes you make to the dictionary will be
  88. # automatically saved to file, let's try this
  89. jack.slogan = "No more schidd!"
  90.  
  91. print
  92.  
  93. # test it ...
  94. print "Modified data:"
  95. personList = [emma, jack, arnie, frank]
  96. for pers in personList:
  97. 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!
Reply With Quote Quick reply to this message  
Reply

Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC