| | |
Starting Python
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
Just an example how to work with Tkinter's color pick dialog ...
python Syntax (Toggle Plain Text)
# select a color and color the root window from Tkinter import * import tkColorChooser #help('tkColorChooser') root = Tk() colorTuple = tkColorChooser.askcolor() print colorTuple # for red = ((255, 0, 0), '#ff0000') print colorTuple[1] # #ff0000 root.configure(bg=colorTuple[1]) root.mainloop()
Last edited by vegaseat; May 15th, 2007 at 7:02 pm. Reason: replaced old php tags
May 'the Google' be with you!
This little code effort came out of one of the forum questions. The function calendar.prmonth(2006, 3) prints a neat little monthly calendar, can the output be assigned to a string for other uses? Here is one way to do this ...
There are simpler methods, but this is a good example of the os.popen() function, or the more updated subprocess.Popen().
Just remember to stick with a proportional font like Courier to line things up correctly.
python Syntax (Toggle Plain Text)
# pipe the output of calendar.prmonth() to a string import subprocess code_str = \ """ import calendar calendar.prmonth(2006, 3) """ # save the code filename = "mar2006.py" fout = open(filename, "w") fout.write(code_str) fout.close() # execute the code and pipe the result to a string test = "python " + filename process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) process.wait() print process.returncode # 0 = success, optional check # read the result to a string month_str = process.stdout.read() print month_str
There are simpler methods, but this is a good example of the os.popen() function, or the more updated subprocess.Popen().
Just remember to stick with a proportional font like Courier to line things up correctly.
Last edited by vegaseat; May 15th, 2007 at 7:05 pm. Reason: replaced old php tags (don't work any more)
May 'the Google' be with you!
You can create a list by concatination and multiplication. The example below shows you a practical approach ...
python Syntax (Toggle Plain Text)
# in English you print first as 1st, second as 2nd and so on # create a list of suffixes for the days of the month (1 to 31) # rather than typing 17 'th' for numbers 4 to 20 you can use 17*['th'] day_suffix = ['st', 'nd', 'rd'] + 17*['th'] + ['st', 'nd', 'rd'] + 7*['th'] + ['st'] print day_suffix """ result = ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st'] """ # now test it for x in range(1, 32): print "%d%s" % (x, day_suffix[x-1]) """ result = 1st 2nd 3rd 4th 5th ... 30th 31st """
Last edited by vegaseat; May 15th, 2007 at 7:07 pm. Reason: replace nonfunctioning php tags
May 'the Google' be with you!
So you want to add an image to your Tkinter GUI program, here is an example ...
python Syntax (Toggle Plain Text)
from Tkinter import * root = Tk() # reads only GIF and PGM/PPM images # for additional formats use Image, ImageTk from PIL # pick a GIF file you have in your working directory imagefile = "Flowers.gif" photo1 = PhotoImage(file=imagefile) width1 = photo1.width() height1 = photo1.height() canvas1 = Canvas(width=width1, height=height1) canvas1.create_image(width1/2.0, height1/2.0, image=photo1) canvas1.pack() root.mainloop()
Last edited by vegaseat; May 15th, 2007 at 7:08 pm. Reason: php
May 'the Google' be with you!
You can use a global variable within a function by prefixing it with the word "global". Here is an example:
The trouble with a global variable is with using it somewhere else in a large program. Everytime you call this function its value will change and may lead to buggy code.
One solution is to use the namespace of the function, making the variable more unique. It gives you a hint where it is used, for example:
Python Syntax (Toggle Plain Text)
# keep track of how many times a function has been accessed # using a global variable, somewhat frowned upon def counter1(): global count # your regular code here count += 1 return count # test it count = 0 # a global variable print counter1() # 1 print counter1() # 2 print count # 2 variable count has changed
One solution is to use the namespace of the function, making the variable more unique. It gives you a hint where it is used, for example:
Python Syntax (Toggle Plain Text)
# avoid the global variable and use the function namespace def counter2(): # your regular code here counter2.count += 1 return counter2.count # test it counter2.count = 0 # now count has counter2 namespace, notice the period print counter2() # 1 print counter2() # 2
drink her pretty
Ever wrote a Python program and wanted to use passwords? What good is password, if the user can simply look at your code and see it?
The module md5 comes to the rescue! It converts the password string to string containing series of hexadecimal numbers. You do that in program1, then copy and paste this hex string into your program (program2).
Here is program1 (keep that to yourself in save place):
This is program2, showing only hex string hashed password, but user has to enter password 'gummy' for md5 to match:
The module md5 comes to the rescue! It converts the password string to string containing series of hexadecimal numbers. You do that in program1, then copy and paste this hex string into your program (program2).
Here is program1 (keep that to yourself in save place):
Python Syntax (Toggle Plain Text)
# program 1, code to generate a hashed password # the result is a series of hexadecimal numbers # it is saved to one text file, so you can # copy and paste it to program2 from any editor import md5 # pick a password you can remember password = "gummy" pw_hashed = md5.md5(password).hexdigest() print pw_hashed # just testing fout = open("MyHashedPassword.txt", "w") fout.write(pw_hashed) fout.close()
Python Syntax (Toggle Plain Text)
# program2, copy hashed password from program1 and assign # it to MYPASSWORDHASH as string, this is all user would see, # if looking at your code import md5 MYPASSWORDHASH = "c1944508a0d871c55b501624c36e0f68" def get_password(): # give it three tries for i in range(3): password = md5.md5(raw_input("Enter your password: ")) password = password.hexdigest() if password == MYPASSWORDHASH: return True return False def main(): if get_password(): print "Success" # do something here with rest of the program code else: print "Failure" # do something else here if __name__ == "__main__": main()
Python allows you to combine a number of statements into one-liner:
Here you have it, but watch out it becomes hard to read and understand at times. Me thinks, me just invented a new word "wewiwowawawiwo". Has nifty ring to it!
Python Syntax (Toggle Plain Text)
str1 = "we willing women want warm winter woollies" list1 = str1.split() print list1 # ['we', 'willing', 'women', 'want', 'warm', 'winter', 'woollies'] list2 = [frag[:2] for frag in list1] print list2 # ['we', 'wi', 'wo', 'wa', 'wa', 'wi', 'wo'] str2 = "".join(list2) print str2 # wewiwowawawiwo # combine all three statements print "".join([frag[:2] for frag in str1.split()])
An example how to run a number of different games or utilities from a menu. The menu is within an infinite while loop with a quit option to break out of the loop. The games or utilities are implemented with a function call ...
python Syntax (Toggle Plain Text)
import random import time import calendar def guess_number(): # random integer 1 to 99 n = random.randint(1, 99) #print n # test while True: guess = int(raw_input("Enter an integer from 1 to 99: ")) if guess < n: print "guess is low" elif guess > n: print "guess is high" else: print "you guessed it!" break def calendar_now(): """show the calendar for the present month""" year_month = time.localtime()[:2] calendar.prmonth(year_month[0], year_month[1]) while True: print "-" * 30 print " Menu" print "to guess a number enter n" print "for a monthly calendar enter m" # more ... print "to quit enter q" print "-" * 30 # also convert any upper case choice to lower case choice = raw_input("enter your choice: ").lower() if choice == 'n': guess_number() elif choice == 'm': calendar_now() # more elif here ... elif choice == 'q': print "thanks for using my program!" break else: print "enter the correct choice!"
Last edited by vegaseat; May 15th, 2007 at 7:46 pm. Reason: php
May 'the Google' be with you!
Someone should write a palindrome program for every computer language there is. Python knows how to handle strings and makes it relatively easy ...
python Syntax (Toggle Plain Text)
# check if a phrase is a palindrome def isPalindrome(phrase): """ take a phrase and convert to all lowercase letters if it matches the reverse spelling then it is a palindrome """ phrase_letters = [c for c in phrase.lower() if c.isalpha()] print phrase_letters # test return (phrase_letters == phrase_letters[::-1]) #phrase = "A man, a plan, a canal, Panama!" phrase = "Madam in Eden I'm Adam" if isPalindrome(phrase): print '"%s" is a palindrome' % phrase else: print '"%s" is not a palindrome' % phrase
Last edited by vegaseat; May 15th, 2007 at 7:47 pm. Reason: php tags changed
May 'the Google' be with you!
You can use Python program to extract picture from web page and save it. I have tested this with Windows XP, might work with other OS:
Python Syntax (Toggle Plain Text)
# load given picture from web page and save it # (you have to be on the internet to do this) import urllib2 import webbrowser import os # find yourself a picture on a web page you like # (right click on the picture, look under properties and copy the address) picture_page = "http://www.google.com/intl/en/images/logo.gif" #webbrowser.open(picture_page) # test # open the web page picture and read it into variable opener1 = urllib2.build_opener() page1 = opener1.open(picture_page) my_picture = page1.read() # open file for binary write and save picture # picture_page[-4:] extracts extension eg. .gif # (most image file extensions have three letters, otherwise modify) filename = "my_image" + picture_page[-4:] print filename # test fout = open(filename, "wb") fout.write(my_picture) fout.close() # was it saved correctly? # test it out ... webbrowser.open(filename)
![]() |
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 |
10 abrupt access accessdenied advice apax api backend basic beginner blogger blogging book bug c++ calculator class code codebox combo coordinates csv daniweb data development dictionary dropdownlist editing event examples excel fedora file form format function game gdata glitch google gui halp handler ideas iframe images input java launcher linux list lists loop microsoft module net news openbsd php problem program programming project projects push py2exe pygame python random redirect reuse rss ruby script scroll silverlight simple snippet software source string sudokusolver table threading tkinter tlapse tutorial ubuntu urllib urllib2 variable vb6 virus web webmaster windows wordgame write wxpython xml







