| | |
Starting Python
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
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:
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.
Python Syntax (Toggle Plain Text)
# 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()
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
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:
Output looks like:
Python Syntax (Toggle Plain Text)
# 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 ...
Python Syntax (Toggle Plain Text)
0 hello 1 2 3 world 4 5 6
Here is an example of how you could use Tkinter, a loop, counter, and some other stuff. Here is the program code:
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"
Python Syntax (Toggle Plain Text)
#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"
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 ...
I have attached a small zip file containing the set of individual pictures that make up the animated GIF.
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)
# mimic an animated GIF displaying a series of GIFs # (an animated GIF was used to create the series of GIFs with a common GIF animator utility) import time from Tkinter import * root = Tk() imagelist = ["dog001.gif","dog002.gif","dog003.gif","dog004.gif","dog005.gif","dog006.gif","dog007.gif"] # extract width and height info photo1 = PhotoImage(file=imagelist[0]) width1 = photo1.width() height1 = photo1.height() canvas1 = Canvas(width=width1, height=height1) canvas1.pack() # loop through the series of GIFs for k in range(0, 1000): print imagelist[k%7], k # test only photo1 = PhotoImage(file=imagelist[k%7]) canvas1.create_image(width1/2.0, height1/2.0, image=photo1) canvas1.update() time.sleep(0.1) root.mainloop()
Last edited by vegaseat; May 15th, 2007 at 7:49 pm. Reason: php tags don't work any longer
May 'the Google' be with you!
Display the letters in a text sorted by their frequency of occurance:
Moderator's note: php tags didn't work properly, replaced them.
python Syntax (Toggle Plain Text)
import string # create a list of lower case letters # ['a', 'b', 'c', 'd', 'e', ... ] alpha_list = list(string.lowercase) text = """The Spell Checker Poem ... Eye halve a spelling chequer It came with my pea sea It plainly marques four my revue Miss steaks eye kin knot sea. Eye strike a key and type a word And weight four it two say Weather eye am wrong oar write It shows me strait a weigh. As soon as a mist ache is maid It nose bee fore two long And eye can put the error rite Its rare lea ever wrong. Eye have run this poem threw it I am shore your pleased two no its letter perfect awl the weigh My chequer tolled me sew. """ # convert text to all lower case letters text = text.lower() # create a list of (frequency, letter) tuples tuple_list = [] for letter in alpha_list: tuple_list.append((text.count(letter), letter)) # sort by frequency (high value first) tuple_list.sort(reverse=True) #print tuple_list # show all letters with frequency above 0 for freq, letter in tuple_list: if freq > 0: print letter, freq """ result = e 67 t 33 a 32 r 29 s 26 ... """
Last edited by vegaseat; May 15th, 2007 at 7:53 pm. Reason: php tags changed
drink her pretty
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)
import os # pick a folder or drive folder = 'C:\\' # pick a file extension extension = ".css" print "All files in %s ending with %s :" % (folder, extension) file_list = [] for (paths, dirs, files) in os.walk(folder): for file in files: if file.endswith(extension): # show progress print '.', file_list.append(os.path.join(paths, file)) for full_filename in file_list: print full_filename
Last edited by vegaseat; May 15th, 2007 at 7:59 pm. Reason: changed php tags
drink her pretty
If you want to create a unique filename in a given folder use the Python module tempfile:
Python Syntax (Toggle Plain Text)
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
So, you want to know the operating system your computer has? This short Python code can tell you:
Python Syntax (Toggle Plain Text)
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
This code allows you to create unique file names containing date and time that can be sorted by age:
Python Syntax (Toggle Plain Text)
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
![]() |
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: How to Pass this Variable?
- Next Thread: Running code for every function in a class
| Thread Tools | Search this Thread |
Tag cloud for code, hints, python, tricks, tutorial
10 abrupt access accessdenied addition advice api applet basic beginner blogger blogging book bug c++ calculator class code codebox combo csv daniweb data development dictionaries dictionary django dropdownlist editing error event examples excel file form format function game gdata google gpl gui halp homework iframe images input java jpeg launcher linux list lists loop microsoft module net news openbsd output php problem program programming project projects py2exe pygame pyqt python random reuse rss ruby script scroll silverlight snippet sort source ssh string sudokusolver table threading tkinter tlapse tutorial ubuntu urllib urllib2 variable vb2008 virus web webmaster windows write wxpython xml







