Starting Python

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Jul 2005
Posts: 1,221
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 138
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #61
Jun 15th, 2006
If you bind GUI event to a function you use a callback function, alas, callback functions are not allowed to have arguments. To remedy situation you can use currying or lambda. Here is an examples of both:
  1. # currying allows GUI callback functions to have arguments
  2. # an alternative is lambda
  3.  
  4. from Tkinter import *
  5.  
  6. class Curry:
  7. """adds arguments to callback function"""
  8. def __init__(self, callback, *args, **kwargs):
  9. self.callback = callback
  10. self.args = args
  11. self.kwargs = kwargs
  12.  
  13. def __call__(self):
  14. # needs Python23 or higher
  15. return self.callback(*self.args, **self.kwargs)
  16.  
  17. def callback(what=None):
  18. print "callback =", what # for testing
  19. if what == 'red':
  20. b1.config(bg="#ff0000")
  21. if what == 'blue':
  22. b2.config(bg="#0000ff")
  23.  
  24. root = Tk()
  25.  
  26. # uses class Curry, since command=callback("red") will not work
  27. b1 = Button(root, text="red", width=6, command=Curry(callback, "red"))
  28. b1.pack(side=LEFT, padx=2, pady=2)
  29.  
  30. # uses lambda instead of Curry
  31. b2 = Button(root, text="blue", width=6, command=lambda: callback("blue"))
  32. b2.pack(side=LEFT, padx=2, pady=2)
  33.  
  34. mainloop()
Editor's Note:
command uses a function object rather then a function call, so arguments have to be added with a lambda or curry wrapper.
Last edited by vegaseat; Sep 22nd, 2006 at 7:03 pm. Reason: added more detail to Bumsfeld's explanation
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,221
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 138
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #62
Jun 15th, 2006
The Python module threading allows you to run a function in the background, as your main program executes. This example adds another feature of Python, called function decoration, the @decorator is added to just above the function you want to run in the background, as example shows:
  1. # running a function in the background with threading
  2. # (apply threading to a function with a function @decorator)
  3.  
  4. import time
  5. import threading
  6.  
  7. def background(f):
  8. def bg_f(*a, **kw):
  9. threading.Thread(target=f, args=a, kwargs=kw).start()
  10. return bg_f
  11.  
  12. # the @decorator forces this function to run in the background
  13. @background
  14. def counter(n):
  15. i = 0
  16. while i < n:
  17. print i
  18. i += 1
  19. time.sleep(0.5) # 0.5 second delay
  20.  
  21. counter(7)
  22. time.sleep(0.4)
  23. print 'hello' # prints hello, before counter prints 1 ...
  24. time.sleep(1.2)
  25. print 'world' # prints world, before counter prints 4 ...
Output looks like:
  1. 0
  2. hello
  3. 1
  4. 2
  5. 3
  6. world
  7. 4
  8. 5
  9. 6
Reply With Quote Quick reply to this message  
Join Date: Jun 2006
Posts: 187
Reputation: Matt Tacular is an unknown quantity at this point 
Solved Threads: 7
Matt Tacular's Avatar
Matt Tacular Matt Tacular is offline Offline
Unverified User

Re: Starting Python

 
0
  #63
Jun 17th, 2006
Here is an example of how you could use Tkinter, a loop, counter, and some other stuff. Here is the program code:

  1. #Created by Mattamus Prime (AKA Matt Tacular)
  2. #This is a simple dice program, pretends to roll a die and show you the progress
  3. #After 25 random screens, it picks one to show.
  4.  
  5. import random
  6. from Tkinter import *
  7. import time
  8.  
  9. def clear():
  10. answerLabel2.configure(text="")
  11. answerLabel3.configure(text="")
  12. answerLabel4.configure(text="")
  13. mainWindow.update()
  14.  
  15. def aDie():
  16. infiniteLoop = True
  17. counter = 0
  18. while infiniteLoop:
  19. number = random.randint(1,6)
  20. time.sleep(0.1)
  21. clear()
  22. counter += 1
  23. if number == 1:
  24. strDie2 = "I I"
  25. strDie3 = "I II I"
  26. strDie4 = "I I"
  27. answerLabel2.configure(text=strDie2)
  28. answerLabel3.configure(text=strDie3)
  29. answerLabel4.configure(text=strDie4)
  30. number = random.randint(1,6)
  31. elif number == 2:
  32. strDie2 = "I II I"
  33. strDie3 = "I I"
  34. strDie4 = "I II I"
  35. answerLabel2.configure(text=strDie2)
  36. answerLabel3.configure(text=strDie3)
  37. answerLabel4.configure(text=strDie4)
  38. number = random.randint(1,6)
  39. elif number == 3:
  40. strDie2 = "I II I"
  41. strDie3 = "I II I"
  42. strDie4 = "I II I"
  43. answerLabel2.configure(text=strDie2)
  44. answerLabel3.configure(text=strDie3)
  45. answerLabel4.configure(text=strDie4)
  46. number = random.randint(1,6)
  47. elif number == 4:
  48. strDie2 = "I II II I"
  49. strDie3 = "I I"
  50. strDie4 = "I II II I"
  51. answerLabel2.configure(text=strDie2)
  52. answerLabel3.configure(text=strDie3)
  53. answerLabel4.configure(text=strDie4)
  54. number = random.randint(1,6)
  55. elif number == 5:
  56. strDie2 = "I II II I"
  57. strDie3 = "I II I"
  58. strDie4 = "I II II I"
  59. answerLabel2.configure(text=strDie2)
  60. answerLabel3.configure(text=strDie3)
  61. answerLabel4.configure(text=strDie4)
  62. number = random.randint(1,6)
  63. elif number == 6:
  64. strDie2 = "I II II I"
  65. strDie3 = "I II II I"
  66. strDie4 = "I II II I"
  67. answerLabel2.configure(text=strDie2)
  68. answerLabel3.configure(text=strDie3)
  69. answerLabel4.configure(text=strDie4)
  70. number = random.randint(1,6)
  71. if counter == 25:
  72. break
  73. mainWindow.update()
  74. mainWindow = Tk()
  75.  
  76. startButton = Button(mainWindow, text="Roll", command=aDie, width=20)
  77. startButton.grid(row=0, column=0)
  78.  
  79. answerLabel = Label(mainWindow, text="IIIIIIIIIIIIIIII", width=20)
  80. answerLabel.grid(row=1, column=0)
  81.  
  82. answerLabel2 = Label(mainWindow, text="I I", width=20)
  83. answerLabel2.grid(row=2, column=0)
  84.  
  85. answerLabel3 = Label(mainWindow, text="I I", width=20)
  86. answerLabel3.grid(row=3, column=0)
  87.  
  88. answerLabel4 = Label(mainWindow, text="I I", width=20)
  89. answerLabel4.grid(row=4, column=0)
  90.  
  91. answerLabel5 = Label(mainWindow, text="IIIIIIIIIIIIIIII", width=20)
  92. answerLabel5.grid(row=5, column=0)
  93.  
  94. mainWindow.mainloop()

What I did, was made a window in Tkinter and in that window made a "Roll" Button. then there are 5 blank labels that get filled by different lines of IIII's depending on what number from 1 - 6 is chosen.

This also shows how you can set up a loop that only ends when the counter hits a certain number, and that only happens when the die has displayed a certain amount of numbers.

And if you want it to run the window with no console, save the code as "filename.pyw" instead of "filename.py"
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,109
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: 943
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
1
  #64
Jun 17th, 2006
You have seen those animated GIF files on webpages, wiggling and jiggling, sometimes fun, sometimes annoyance. I wanted an animated GIF file to animate on Tkinter, but only got a still picture.

An animated GIF file is really just a series of GIF files, like a series of frames in a movie. You can take one of the common GIF Animator Utlities and extract the individual GIF files that make up the series.

Next, loop these image files through the regular canvas.create_image() function, delay each frame to mimic animation, and you have your custom made movie. Here is the code example ...
  1. # mimic an animated GIF displaying a series of GIFs
  2. # (an animated GIF was used to create the series of GIFs with a common GIF animator utility)
  3.  
  4. import time
  5. from Tkinter import *
  6.  
  7. root = Tk()
  8.  
  9. imagelist = ["dog001.gif","dog002.gif","dog003.gif","dog004.gif","dog005.gif","dog006.gif","dog007.gif"]
  10.  
  11. # extract width and height info
  12. photo1 = PhotoImage(file=imagelist[0])
  13. width1 = photo1.width()
  14. height1 = photo1.height()
  15. canvas1 = Canvas(width=width1, height=height1)
  16. canvas1.pack()
  17.  
  18. # loop through the series of GIFs
  19. for k in range(0, 1000):
  20. print imagelist[k%7], k # test only
  21. photo1 = PhotoImage(file=imagelist[k%7])
  22. canvas1.create_image(width1/2.0, height1/2.0, image=photo1)
  23. canvas1.update()
  24. time.sleep(0.1)
  25.  
  26. root.mainloop()
I have attached a small zip file containing the set of individual pictures that make up the animated GIF.
Last edited by vegaseat; May 15th, 2007 at 7:49 pm. Reason: php tags don't work any longer
Attached Files
File Type: zip Tk_AnimatedGIF1.zip (9.0 KB, 28 views)
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,546
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 174
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting Python

 
-1
  #65
Jun 28th, 2006
Display the letters in a text sorted by their frequency of occurance:
  1. import string
  2.  
  3. # create a list of lower case letters
  4. # ['a', 'b', 'c', 'd', 'e', ... ]
  5. alpha_list = list(string.lowercase)
  6.  
  7. text = """The Spell Checker Poem ...
  8.  
  9. Eye halve a spelling chequer
  10. It came with my pea sea
  11. It plainly marques four my revue
  12. Miss steaks eye kin knot sea.
  13.  
  14. Eye strike a key and type a word
  15. And weight four it two say
  16. Weather eye am wrong oar write
  17. It shows me strait a weigh.
  18. As soon as a mist ache is maid
  19. It nose bee fore two long
  20. And eye can put the error rite
  21. Its rare lea ever wrong.
  22.  
  23. Eye have run this poem threw it
  24. I am shore your pleased two no
  25. its letter perfect awl the weigh
  26. My chequer tolled me sew.
  27. """
  28.  
  29. # convert text to all lower case letters
  30. text = text.lower()
  31.  
  32. # create a list of (frequency, letter) tuples
  33. tuple_list = []
  34. for letter in alpha_list:
  35. tuple_list.append((text.count(letter), letter))
  36.  
  37. # sort by frequency (high value first)
  38. tuple_list.sort(reverse=True)
  39. #print tuple_list
  40.  
  41. # show all letters with frequency above 0
  42. for freq, letter in tuple_list:
  43. if freq > 0:
  44. print letter, freq
  45.  
  46. """
  47. result =
  48. e 67
  49. t 33
  50. a 32
  51. r 29
  52. s 26
  53. ...
  54.  
  55. """
Moderator's note: php tags didn't work properly, replaced them.
Last edited by vegaseat; May 15th, 2007 at 7:53 pm. Reason: php tags changed
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Jan 2006
Posts: 70
Reputation: jamshid is an unknown quantity at this point 
Solved Threads: 0
jamshid's Avatar
jamshid jamshid is offline Offline
Junior Poster in Training

Re: Starting Python

 
-1
  #66
Jul 18th, 2006
Really nice sharings here .... thanks i hope it will continue
Impossible is Nothing
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,546
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 174
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting Python

 
0
  #67
Jul 21st, 2006
This short code finds all files in a given drive or folder/directory that end with a selected file extension. It also checks all the subdirectories:
  1. import os
  2.  
  3. # pick a folder or drive
  4. folder = 'C:\\'
  5. # pick a file extension
  6. extension = ".css"
  7.  
  8. print "All files in %s ending with %s :" % (folder, extension)
  9. file_list = []
  10. for (paths, dirs, files) in os.walk(folder):
  11. for file in files:
  12. if file.endswith(extension):
  13. # show progress
  14. print '.',
  15. file_list.append(os.path.join(paths, file))
  16.  
  17. print
  18.  
  19. for full_filename in file_list:
  20. print full_filename
Last edited by vegaseat; May 15th, 2007 at 7:59 pm. Reason: changed php tags
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,546
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 174
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting Python

 
0
  #68
Jul 25th, 2006
If you want to create a unique filename in a given folder use the Python module tempfile:
  1. import tempfile
  2.  
  3. # creates a random file (text=True is textfile, text=False is binary file)
  4. ext = '.txt'
  5. pfx = 'tmp'
  6. dir = 'C:\\Temp'
  7. filename = tempfile.mkstemp(suffix=ext, prefix=pfx, dir=dir, text=True)[1]
  8. print filename # eg. C:\Temp\tmpsnrfgk.txt
  9.  
  10. # test it ...
  11. fout = open(filename, 'w')
  12. fout.write("Just a text file")
  13. fout.close()
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,221
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 138
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #69
Jul 28th, 2006
So, you want to know the operating system your computer has? This short Python code can tell you:
  1. import sys
  2.  
  3. operating_system = sys.platform
  4. print operating_system # eg. win32
  5.  
  6. if operating_system[:3] == 'win':
  7. print "Your OS is Windows"
  8. elif operating_system[:5] == 'linux':
  9. print "Your OS is Linux"
  10.  
  11. # or ........
  12.  
  13. import os
  14.  
  15. print os.name # eg. nt
  16. print os.environ['OS'] # eg. Windows_NT
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,221
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 138
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #70
Aug 5th, 2006
This code allows you to create unique file names containing date and time that can be sorted by age:
  1. import time
  2.  
  3. # using year_month_day_hour_min_sec (24 hour foemat)
  4. filename1 = time.strftime('%Y_%m_%d_%H_%M_%S.dat')
  5. print filename1 # eg. 2006_08_05_20_57_56.dat
  6.  
  7. # or using seconds since epoch
  8. filename2 = str(int(time.time())) + ".dat"
  9. print filename2 # eg. 1154825876.dat
Reply With Quote Quick reply to this message  
Reply

Tags
code, hints, python, tricks, tutorial

Message:



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



Tag cloud for code, hints, python, tricks, tutorial
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC