943,714 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Unsolved
  • Views: 128887
  • Python RSS
You are currently viewing page 7 of this multi-page discussion thread; Jump to the first page
Jun 15th, 2006
1

Re: Starting Python

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:
Python Syntax (Toggle Plain Text)
  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
Reputation Points: 404
Solved Threads: 180
Nearly a Posting Virtuoso
bumsfeld is offline Offline
1,422 posts
since Jul 2005
Jun 15th, 2006
0

Re: Starting Python

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:
Python Syntax (Toggle Plain Text)
  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:
Python Syntax (Toggle Plain Text)
  1. 0
  2. hello
  3. 1
  4. 2
  5. 3
  6. world
  7. 4
  8. 5
  9. 6
Reputation Points: 404
Solved Threads: 180
Nearly a Posting Virtuoso
bumsfeld is offline Offline
1,422 posts
since Jul 2005
Jun 17th, 2006
0

Re: Starting Python

Here is an example of how you could use Tkinter, a loop, counter, and some other stuff. Here is the program code:

Python Syntax (Toggle Plain Text)
  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"
Reputation Points: 10
Solved Threads: 7
Unverified User
Matt Tacular is offline Offline
187 posts
since Jun 2006
Jun 17th, 2006
2

Re: Starting Python

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 ...
python Syntax (Toggle Plain Text)
  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.
Attached Files
File Type: zip Tk_AnimatedGIF1.zip (9.0 KB, 167 views)
Last edited by vegaseat; May 15th, 2007 at 7:49 pm. Reason: php tags don't work any longer
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Jun 28th, 2006
-1

Re: Starting Python

Display the letters in a text sorted by their frequency of occurance:
python Syntax (Toggle Plain Text)
  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
Reputation Points: 625
Solved Threads: 211
Posting Virtuoso
Ene Uran is offline Offline
1,704 posts
since Aug 2005
Jul 18th, 2006
-1

Re: Starting Python

Really nice sharings here .... thanks i hope it will continue
Reputation Points: 8
Solved Threads: 0
Junior Poster in Training
jamshid is offline Offline
70 posts
since Jan 2006
Jul 21st, 2006
0

Re: Starting Python

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:
python Syntax (Toggle Plain Text)
  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
Reputation Points: 625
Solved Threads: 211
Posting Virtuoso
Ene Uran is offline Offline
1,704 posts
since Aug 2005
Jul 25th, 2006
0

Re: Starting Python

If you want to create a unique filename in a given folder use the Python module tempfile:
Python Syntax (Toggle Plain Text)
  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()
Reputation Points: 625
Solved Threads: 211
Posting Virtuoso
Ene Uran is offline Offline
1,704 posts
since Aug 2005
Jul 28th, 2006
0

Re: Starting Python

So, you want to know the operating system your computer has? This short Python code can tell you:
Python Syntax (Toggle Plain Text)
  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
Reputation Points: 404
Solved Threads: 180
Nearly a Posting Virtuoso
bumsfeld is offline Offline
1,422 posts
since Jul 2005
Aug 5th, 2006
1

Re: Starting Python

This code allows you to create unique file names containing date and time that can be sorted by age:
Python Syntax (Toggle Plain Text)
  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
Reputation Points: 404
Solved Threads: 180
Nearly a Posting Virtuoso
bumsfeld is offline Offline
1,422 posts
since Jul 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: help with Quadratic Formula Code
Next Thread in Python Forum Timeline: First time using cx_Freeze





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC