1,105,556 Community Members

Starting Python

Member Avatar
bumsfeld
Posting Virtuoso
1,537 posts since Jul 2005
Reputation Points: 399 [?]
Q&As Helped to Solve: 261 [?]
Skill Endorsements: 7 [?]
 
1
 

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.

Member Avatar
bumsfeld
Posting Virtuoso
1,537 posts since Jul 2005
Reputation Points: 399 [?]
Q&As Helped to Solve: 261 [?]
Skill Endorsements: 7 [?]
 
0
 

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
Matt Tacular
Junior Poster
187 posts since Jun 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 7 [?]
Skill Endorsements: 0 [?]
Unverified Member
 
0
 

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"

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
3
 

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 ...

# 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()

I have attached a small zip file containing the set of individual pictures that make up the animated GIF.

Attachments Tk_AnimatedGIF1.zip (9.04KB)
Member Avatar
Ene Uran
Posting Virtuoso
1,822 posts since Aug 2005
Reputation Points: 610 [?]
Q&As Helped to Solve: 278 [?]
Skill Endorsements: 10 [?]
 
0
 

Display the letters in a text sorted by their frequency of occurance:

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
...
 
"""

Moderator's note: php tags didn't work properly, replaced them.

Member Avatar
jamshid
Junior Poster in Training
70 posts since Jan 2006
Reputation Points: -2 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Really nice sharings here .... thanks i hope it will continue

Member Avatar
Ene Uran
Posting Virtuoso
1,822 posts since Aug 2005
Reputation Points: 610 [?]
Q&As Helped to Solve: 278 [?]
Skill Endorsements: 10 [?]
 
0
 

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:

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))
 
print
 
for full_filename in file_list:
    print full_filename
Member Avatar
Ene Uran
Posting Virtuoso
1,822 posts since Aug 2005
Reputation Points: 610 [?]
Q&As Helped to Solve: 278 [?]
Skill Endorsements: 10 [?]
 
1
 

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()
Member Avatar
bumsfeld
Posting Virtuoso
1,537 posts since Jul 2005
Reputation Points: 399 [?]
Q&As Helped to Solve: 261 [?]
Skill Endorsements: 7 [?]
 
1
 

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
Member Avatar
bumsfeld
Posting Virtuoso
1,537 posts since Jul 2005
Reputation Points: 399 [?]
Q&As Helped to Solve: 261 [?]
Skill Endorsements: 7 [?]
 
2
 

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
Member Avatar
Ene Uran
Posting Virtuoso
1,822 posts since Aug 2005
Reputation Points: 610 [?]
Q&As Helped to Solve: 278 [?]
Skill Endorsements: 10 [?]
 
0
 

Version 2.5 of Python final release is planned for 12sep2006. It will have a few nice improvements. On of them is class partial. Bumsfeld has talked about adding arguments to GUI callback functions earlier. This new class will help. Here is a fun example that can be used with Python 2.4:

# class partial is similar to currying to add arguments
# starting with Python 2.5 you can simply import class partial
# using: from functools import partial

from Tkinter import Tk, Canvas, Button


class partial(object):
    """partial application using both positional and keyword arguments"""
    def __init__(*args, **kw):
        self = args[0]
        self.fn, self.args, self.kw = (args[1], args[2:], kw)

    def __call__(self, *args, **kw):
        if kw and self.kw:
            d = self.kw.copy()
            d.update(kw)
        else:
            d = kw or self.kw
        return self.fn(*(self.args + args), **d)


root = Tk()
c = Canvas(root,width=200,height=50)
c.pack()

color_list = ['red','blue','green','yellow','black','white']
for color in color_list:
    # uses class partial to construct callbacks for Tkinter widgets
    # called as though it were a function
    # basically passes/implements c.config(bg=color)
    b = Button(root, text=color, command=partial(c.config, bg=color))
    b.pack(side='left')

root.mainloop()

Edit: A correction has been made, in the final production release of Python 2.5 partial() is in module functools.

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
2
 

Just a few odd things you can do with lists in Python ...

# create a list of char 'a' to 'z'
list_a2z = map(chr, range(ord('a'), ord('z')))
print list_a2z
 
# create a list of char using a generator expression
char_list = list(x for x in "abcd")
print char_list # ['a', 'b', 'c', 'd']
 
# create an enumerated char list
enumchar_list = list(enumerate('abcd'))
print enumchar_list  # [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
 
# can be easily changed to a dictionary
dict1 = dict(enumchar_list)  
print dict1  # {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
# swap key:value of dictionary
dict2 = dict([(v, k) for (k, v) in dict1.iteritems()])
print dict2  # {'a': 0, 'c': 2, 'b': 1, 'd': 3}
 
print
 
x = [1, 2, 3, 4]
# create a listreverseiterator object, leaves the source unchanged
# reversed() needs Python24 and higher
rx = reversed(x)
print rx        # <listreverseiterator object at 0x00AE2D70>
print "original list:"
print x
print "reversed list:"
print list(rx)  # [4, 3, 2, 1]
 
print
 
# reset the iterator object and iterate
rx = reversed(x)
for k in rx: 
    print k,    # 4 3 2 1
print
 
print
 
# create a list with duplicate items/elements
list1 = list(x for x in "abcdefab")
print list1  # ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b']
 
print
 
# weed out duplicate items from this list via list comprehension
list2 = []
# translation: add item from list1 to list2 if it's not there

[list2.append(item) for item in list1 if not list2.count(item)]
print list2  # ['a', 'b', 'c', 'd', 'e', 'f']
 
print
 
# same but using a set, this will change order
# set uses a hashed order
set1 = set(list1)
print set1        # set(['a', 'c', 'b', 'e', 'd', 'f'])
print list(set1)  # ['a', 'c', 'b', 'e', 'd', 'f']
 
print
 
# working with a nested lists
list3 = [1 ,'Dick', 2, ['Mary', 7, 9, [700, 777]], 13]
 
print list3[1]        # Dick
print list3[3]        # ['Mary', 7, 9, [700, 777]]
print list3[3][0]     # Mary
print list3[3][3]     # [700, 777]
print list3[3][3][1]  # 777
 
# make a shallow copy of list 3
list4 = list(list3)  # or list4 = list3[:]
print list3
print list4
 
# change Dick to Mike in list3
list3[1] = 'Mike'
# test it ...
print list3  # [1, 'Mike', 2, ['Mary', 7, 9, [700, 777]], 13]
print list4  # [1, 'Dick', 2, ['Mary', 7, 9, [700, 777]], 13]  okay!
 
# change the more nested Mary to Sue in list3
list3[3][0] = 'Sue'
# test it ...
print list3  # [1, 'Mike', 2, ['Sue', 7, 9, [700, 777]], 13]
print list4  # [1, 'Dick', 2, ['Sue', 7, 9, [700, 777]], 13]  oops!
 
# to make a true copy of a nested list use function deepcopy() from module copy
import copy
 
list5 = [1 ,'Dick', 2, ['Mary', 7, 9, [700, 777]], 13]
list6 = copy.deepcopy(list5)
 
# change Mary to Sue in list5
list5[3][0] = 'Sue'
# test it ...
print list5  # [1, 'Dick', 2, ['Sue', 7, 9, [700, 777]], 13]
print list6  # [1, 'Dick', 2, ['Mary', 7, 9, [700, 777]], 13]  that's better!
 
print
 
# make a list of ten zeroes
list7 =  [0] * 10
print list7  # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 
list7[0] = 77
print list7   # [77, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 
# wonder what the result will be?
list8 = list7 * 2
print list8   # [77, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 
print
 
def minmax4(lst, typ):
    """return min/max of mixed list lst for items of type typ"""
    temp = [x for x in lst if isinstance(x, typ)]
    return min(temp), max(temp)
 
# minmax4() test ...
mixed_list = [11, 'Dick', 12, 'Mary', 7, 'Zoe', 9, 700, 777, 'Paul', 13456789]
print mixed_list
 
print "The min and max of the integers are:"
mn, mx = minmax4(mixed_list, int)
print "minimum = %s  maximum = %s" % (mn, mx)
 
print "The min and max of the strings are:"
mn, mx = minmax4(mixed_list, str)
print "minimum = %s  maximum = %s" % (mn, mx)
 
"""
minmax4() test -->
[11, 'Dick', 12, 'Mary', 7, 'Zoe', 9, 700, 777, 'Paul', 13456789]
The min and max of the integers are:
minimum = 7  maximum = 13456789
The min and max of the strings are:
minimum = Dick  maximum = Zoe
"""

Note: the code field is for php, but it gives some color to Python code. Vanity on my part!
Note+: php tags don't work any longer, don't use them, eat crow!

Member Avatar
bumsfeld
Posting Virtuoso
1,537 posts since Jul 2005
Reputation Points: 399 [?]
Q&As Helped to Solve: 261 [?]
Skill Endorsements: 7 [?]
 
0
 

There are situations where you want to add s to string to indicate plural. Here is example:

print "<%s>" % ('s' * 0)  # <>
print "<%s>" % ('s' * 1)  # <s>
print 1 != 1              # False --> 0
print 2 != 1              # True --> 1

# add an 's' to indicate plural when k is not 1
for k in range(1, 4):
    print "The for loop ran %d time%s" % (k, 's'*(k != 1))

"""
The for loop ran 1 time
The for loop ran 2 times
The for loop ran 3 times
"""
Member Avatar
Ene Uran
Posting Virtuoso
1,822 posts since Aug 2005
Reputation Points: 610 [?]
Q&As Helped to Solve: 278 [?]
Skill Endorsements: 10 [?]
 
0
 

If you get confused with the builtin functions input() and raw_input() (Who came up with raw_input anyway?), you can change the names of these functions in your program to something you understand better:

input_str = raw_input
input_int = input
# now you can use ...
name = input_str("Enter your name: ")
age = input_int("Enter your age: ")

print "Hi %s, you are %d old!" % (name, age)
# or if this is more readable use this ...
print "Hi %(name)s, you are %(age)d old!" % vars()
Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
2
 

This short function tells you if the items in a given list are unique (no duplicates) ...

# are the items in a list unique:
def is_list_unique(list1):
    """are the items in list1 unique, returns True or False"""
    return len(list1) == len(set(list1))
 
list1 = [1, 2, 3, 4, 5]
print is_list_unique(list1)  # True
 
list2 = [1, 2, 3, 3, 4, 5]
print is_list_unique(list2)  # False
Member Avatar
chris99
Junior Poster
123 posts since Sep 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Ever wanted to make a text adventure? It's quite simple:

#First you define the start of the game:
def game_start():
    print '''Your story opening here'''
    room1() #takes you to the function room 1, when you have 
    #defined it.
 
def room1():
    """This code will print a description of your room1,
    say, the foyer of a house."""
    room1_prompt() #You will take the user to the prompt
 
def room1_desc():
    """The description here is called every time a command such as
    'look' is typed into the prompt."""
   room1_prompt()
 
def room1_prompt():
    """Here, you will take input to determine what will happen. You
    sort all the problems with an if-elif-else loop."""
    promptR1 = raw_input("Type a command: ").lower() 
# The .lower
#will convert the user input all to one case, so that it is
#interpreted as:
#Look.lower() == look == "look"
 
    if promptR1 == "look":
        room1_desc()
    elif promptR1 == "help":
#defined function for help, to print a list of commands
    else:
       print "That is invalid"
       room1_prompt()

This code will create a room in three functions, one to load the room and give a description; the prompt, which acts as a hub from which all other commands are reached. Each room shares a help statement, but where you go or what you can look at is all done in the prompts.

I hope that this helped, I'm new at this language too, but I'm making a text adventure so I know hat I'm on about! :P

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
2
 

Do you want to check if two files are equal? Easy with Python module filecmp ...

# compare two files and check if they are equal
# files can be binary or text based
import filecmp
 
# pick two files you want to compare ...
file1 = "Boing1.wav"
file2 = "Boing2.wav"
if filecmp.cmp(file1, file2):
    print "Files %s and %s are identical" % (file1, file2)
else:
    print "Files %s and %s differ!" % (file1, file2)
Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
0
 

A short Python code to show you how to create a card game. Unzip the attached card image file into a directory that you want the program to use.

The code shows you how to create a list of card names which match the filenames of the images (+.gif), shuffle the list, pick a hand of five cards, and display the cards in a Tkinter GUI. The image objects are stored indexed by card name in a dictionary ...

# using Tkinter to display a hand of 5 random card images
# each time you click the canvas
# (images are in GIF format for Tkinter to display properly)
 
from Tkinter import *
import random
 
root = Tk()
root.title("Click me!")
 
def create_cards():
    """
    create a list of 52 cards
    suit: club=C, diamond=D, heart=H spade=S
    rank: ace=A, 10=T, jack=J, queen=Q, king=K, numbers=2..9
    ace of spade would be SA, 8 of heart would be H8 and so on ...
    """
    return [ suit + rank for suit in "CDHS" for rank in "A23456789TJQK" ]
 
def shuffle_cards(card_list):
    """random shuffle a list of cards"""
    # make a copy of the original list
    card_list1 = card_list[:]
    random.shuffle(card_list1)
    return card_list1
 
def pick_5cards(card_list):
    """pick five cards from the shuffled list"""
    return card_list[:5]
 
def create_images():
    """create all card images as a card_name:image_object dictionary"""
    card_list = create_cards()
    image_dict = {}
    for card in card_list:
        # all images have filenames the match the card_list names + extension .gif
        image_dict[card] = PhotoImage(file=image_dir+card+".gif")
        #print image_dir+card+".gif"  # test
    return image_dict
 
def next_hand(event):
    """create the card list, shuffle, pick five cards and display them"""
    card_list = create_cards()
    card_list = shuffle_cards(card_list)
    card_list = pick_5cards(card_list)
    root.title(card_list)  # test
 
    # now display the card images at the proper location on the canvas
    x = 10
    y = 10
    for card in card_list:
        #print card, x, y  # test
        canvas1.create_image(x, y, image=image_dict[card], anchor=NW)
        # calculate each NW corner x, y
        x += 90
 
# change this to the directory your card GIFs are in
image_dir = "D:/Python24/Atest/images/Cards_gif/"
 
# load a sample card to get the size
photo1 = PhotoImage(file=image_dir+"C2.gif")
 
# make canvas 5 times the width of a card + 100
width1 = 5 * photo1.width() + 100
height1 = photo1.height() + 20
canvas1 = Canvas(width=width1, height=height1)
canvas1.pack()
 
# now load all card images into a dictionary
image_dict = create_images()
#print image_dict  # test
 
# bind left mouse click on canvas to next_hand display
canvas1.bind('<Button-1>', next_hand)
 
root.mainloop()

From there you can expand the game to discard and replace selected cards and to analyze, if you have a poker hand.

Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.

Attachments Cards_gif.zip (53.7KB)
Member Avatar
bumsfeld
Posting Virtuoso
1,537 posts since Jul 2005
Reputation Points: 399 [?]
Q&As Helped to Solve: 261 [?]
Skill Endorsements: 7 [?]
 
1
 

You have two similar lists and want to see what items are in list1 that are not in list2 and vice versa. The trick is to convert them into sets and take the difference:

color_list1 = ["red","green","blue","purple","yellow","violet","white","cyan",
   "magenta","turquoise","black","lightblue","grey","lightgrey","darkgrey",
   "lightgreen","teal","pink","darkblue","darkred","darkgreen","orchid","beige"]

color_list2 = ["red","green","blue","purple","yellow","orchid","grey","white",
   "cyan","magenta","turquoise","limegreen","lightblue","lightgrey","darkgrey",
   "lightgreen","tan","darkblue","darkred","darkgreen","violet","pink","beige"]

print "color_list1 =", color_list1
print "-"*70  # 70 dashes
print "color_list2 =", color_list2
print "-"*70

# convert lists to sets
color_set1 = set(color_list1)
color_set2 = set(color_list2)

print "These are the colors of color_list1 that are not in color_list2:"
print color_set1 - color_set2
print "-"*70

print "These are the colors of color_list2 that are not in color_list1:"
print color_set2 - color_set1
Member Avatar
Ene Uran
Posting Virtuoso
1,822 posts since Aug 2005
Reputation Points: 610 [?]
Q&As Helped to Solve: 278 [?]
Skill Endorsements: 10 [?]
 
0
 

Let's draw some colorful shapes on a Tkinter canvas and clear the canvas after a given amount of seconds:

# clear the Tkinter canvas after drawing some shapes

from Tkinter import *

root = Tk()
root.title("clear canvas after 5 seconds")

# create the canvas to draw upon
# default background color (bg) is "facecolor"
c = Canvas(root, width=500, height=420, bg="white")
c.pack()

# draw a maroon line from x1=10,y1=20 to x2=200,y2=100
# default width=1 and fill="black"
c.create_line(10, 20, 200, 100, width=2, fill="maroon")

# draw an ovel inside a box with corner coordinates x1=200,y1=20 and x2=450,y2=100
# fill the oval blue (if the box is square a circle is drawn)
c.create_oval(200, 20, 450, 100, fill="blue")

# draw a red rectangle with corner coordinates x1=50,y1=150 and x2=300,y2=400
c.create_rectangle(50, 150, 300, 400, fill="red")

# since the above rectangle is a square stuff a green circle in it
c.create_oval(50, 150, 300, 400, fill="green")

root.after(5000, c.delete, ALL)  # after 5000 ms call c.delete(ALL)

root.mainloop()
You
Post:
Start New Discussion
View similar articles that have also been tagged: