User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 425,917 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 1,704 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser: Programming Forums
Views: 54764 | Replies: 150
Reply
Join Date: Jul 2005
Location: France
Posts: 1,005
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 45
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Veteran Poster

Re: Starting Python

  #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:
# currying allows GUI callback functions to have arguments
# an alternative is lambda

from Tkinter import *

class Curry:
    """adds arguments to callback function"""
    def __init__(self, callback, *args, **kwargs):
        self.callback = callback
        self.args = args
        self.kwargs = kwargs

    def __call__(self):
        # needs Python23 or higher
        return self.callback(*self.args, **self.kwargs)

def callback(what=None):
    print "callback =", what  # for testing
    if what == 'red':
        b1.config(bg="#ff0000")
    if what == 'blue':
        b2.config(bg="#0000ff")

root = Tk()

# uses class Curry, since command=callback("red") will not work
b1 = Button(root, text="red", width=6, command=Curry(callback, "red"))
b1.pack(side=LEFT, padx=2, pady=2)

# uses lambda instead of Curry
b2 = Button(root, text="blue", width=6, command=lambda: callback("blue"))
b2.pack(side=LEFT, padx=2, pady=2)

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 6:03 pm. Reason: added more detail to Bumsfeld's explanation
Reply With Quote  
Join Date: Jul 2005
Location: France
Posts: 1,005
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 45
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Veteran Poster

Re: Starting Python

  #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:
# running a function in the background with threading
# (apply threading to a function with a function @decorator)

import time
import threading

def background(f):
    def bg_f(*a, **kw):
        threading.Thread(target=f, args=a, kwargs=kw).start()
    return bg_f

# the @decorator forces this function to run in the background
@background
def counter(n):
    i = 0
    while i < n:
        print i
        i += 1
        time.sleep(0.5)  # 0.5 second delay

counter(7)
time.sleep(0.4)
print 'hello'   # prints hello, before counter prints 1 ...
time.sleep(1.2)
print 'world'   # prints world, before counter prints 4 ...
Output looks like:
0
hello
1
2
3
world
4
5
6
Reply With Quote  
Join Date: Jun 2006
Location: America
Posts: 186
Reputation: Matt Tacular is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 2
Matt Tacular's Avatar
Matt Tacular Matt Tacular is offline Offline
Junior Poster

Re: Starting Python

  #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:

#Created by Mattamus Prime (AKA Matt Tacular)
#This is a simple dice program, pretends to roll a die and show you the progress
#After 25 random screens, it picks one to show.

import random
from Tkinter import *
import time

def clear():
    answerLabel2.configure(text="")
    answerLabel3.configure(text="")
    answerLabel4.configure(text="")
    mainWindow.update()
    
def aDie():
    infiniteLoop = True
    counter = 0
    while infiniteLoop:
        number = random.randint(1,6)
        time.sleep(0.1)
        clear()
        counter += 1
        if number == 1:
            strDie2 = "I              I"
            strDie3 = "I      II      I"
            strDie4 = "I              I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        elif number == 2:
            strDie2 = "I    II        I"
            strDie3 = "I              I"
            strDie4 = "I        II    I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        elif number == 3:
            strDie2 = "I        II    I"
            strDie3 = "I      II      I"
            strDie4 = "I    II        I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        elif number == 4:
            strDie2 = "I    II  II    I"
            strDie3 = "I              I"
            strDie4 = "I    II  II    I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        elif number == 5:
            strDie2 = "I    II  II    I"
            strDie3 = "I      II      I"
            strDie4 = "I    II  II    I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        elif number == 6:
            strDie2 = "I    II  II    I"
            strDie3 = "I    II  II    I"
            strDie4 = "I    II  II    I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        if counter == 25:
            break
        mainWindow.update()
mainWindow = Tk()
    
startButton = Button(mainWindow, text="Roll", command=aDie, width=20)
startButton.grid(row=0, column=0)

answerLabel = Label(mainWindow, text="IIIIIIIIIIIIIIII", width=20)
answerLabel.grid(row=1, column=0)

answerLabel2 = Label(mainWindow, text="I              I", width=20)
answerLabel2.grid(row=2, column=0)

answerLabel3 = Label(mainWindow, text="I              I", width=20)
answerLabel3.grid(row=3, column=0)

answerLabel4 = Label(mainWindow, text="I              I", width=20)
answerLabel4.grid(row=4, column=0)

answerLabel5 = Label(mainWindow, text="IIIIIIIIIIIIIIII", width=20)
answerLabel5.grid(row=5, column=0)

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  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,468
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 10
Solved Threads: 176
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #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 6:49 pm. Reason: php tags don't work any longer
Attached Files
File Type: zip Tk_AnimatedGIF1.zip (9.0 KB, 20 views)
May 'the Google' be with you!
Reply With Quote  
Join Date: Aug 2005
Posts: 1,133
Reputation: Ene Uran is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 66
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Veteran Poster

Re: Starting Python

  #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 6:53 pm. Reason: php tags changed
drink her pretty
Reply With Quote  
Join Date: Jan 2006
Location: Balkh
Posts: 67
Reputation: jamshid is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
jamshid's Avatar
jamshid jamshid is offline Offline
Junior Poster in Training

Re: Starting Python

  #66  
Jul 18th, 2006
Really nice sharings here .... thanks i hope it will continue
Impossible is Nothing
Reply With Quote  
Join Date: Aug 2005
Posts: 1,133
Reputation: Ene Uran is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 66
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Veteran Poster

Re: Starting Python

  #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 6:59 pm. Reason: changed php tags
drink her pretty
Reply With Quote  
Join Date: Aug 2005
Posts: 1,133
Reputation: Ene Uran is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 66
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Veteran Poster

Re: Starting Python

  #68  
Jul 25th, 2006
If you want to create a unique filename in a given folder use the Python module tempfile:
import tempfile

# creates a random file (text=True is textfile, text=False is binary file)
ext = '.txt'
pfx = 'tmp'
dir = 'C:\\Temp'
filename = tempfile.mkstemp(suffix=ext, prefix=pfx, dir=dir, text=True)[1]
print filename  # eg. C:\Temp\tmpsnrfgk.txt

# test it ...
fout = open(filename, 'w')
fout.write("Just a text file")
fout.close()
drink her pretty
Reply With Quote  
Join Date: Jul 2005
Location: France
Posts: 1,005
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 45
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Veteran Poster

Re: Starting Python

  #69  
Jul 28th, 2006
So, you want to know the operating system your computer has? This short Python code can tell you:
import sys

operating_system = sys.platform
print operating_system              # eg.  win32

if operating_system[:3] == 'win':
    print "Your OS is Windows"
elif operating_system[:5] == 'linux':
    print "Your OS is Linux"

# or ........

import os

print os.name              # eg.  nt
print os.environ['OS']   # eg.  Windows_NT
Reply With Quote  
Join Date: Jul 2005
Location: France
Posts: 1,005
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 45
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Veteran Poster

Re: Starting Python

  #70  
Aug 5th, 2006
This code allows you to create unique file names containing date and time that can be sorted by age:
import time

# using year_month_day_hour_min_sec  (24 hour foemat)
filename1 = time.strftime('%Y_%m_%d_%H_%M_%S.dat')
print filename1  # eg.   2006_08_05_20_57_56.dat

# or using seconds since epoch
filename2 = str(int(time.time())) + ".dat"
print filename2  # eg.  1154825876.dat
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

DaniWeb Python Marketplace
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes

Similar Threads
Other Threads in the Python Forum

All times are GMT -4. The time now is 8:20 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC