Greetings:

I have been working with code examples (from the good people on this site) and I have been learning quite a bit about Python and becoming more comfortable with.

The program I am working on is being done in pieces, the GUI being really the primary area of problems thus far as I am unfamiliar with this aspect of programming.

The submitted code below is a merge of two sets of code. Allow me to explain what I am trying to achieve with this code (** this code is really only a test which I shall expand upon greatly if\ when it works):

I present a button where a player chooses to "play"; in this simple example, the button will initiate a RNG, which in turn will return a random value 1-52 (in this example, I am just allowing a return of one number for testing-- I already know the RNG works. My issue is that everything seems to work (including the IF test statement) but the display of final result (a single image from my working folder named "king_emp.GIF") does not occur, the loading of this image onto the canvas.

from Tkinter import *
from random  import*
import random

#=======================================def(s)
def show_image2():
    canvas1.create_image(50, 320, image=photo2)


def shuffle(x):
    # random.shuffle(x) would be simpler
    for i in xrange(len(x)-1, 0, -1):
        #pick an element in x[:i+1] with which to exchange x[i]
        j = int(random.random() * (i+1))
        x[i], x[j] = x[j], x[i]
    #print x  # test
    canvas1.config(text=x[0])# [0] acts to choose only 1 of 52


image2 = "king_emp.GIF"    

#=======================================canvas set-up

canvas1 = Tk()
canvas1.title('Heart Test1')

canvas1 = Label(canvas1, fg='pink', bg='purple')
canvas1.grid(row=1, column=0, columnspan=4)

#=======================================image handling


#photo2 = PhotoImage(file=image2)

#=======================================var & list for RNG

x = [0] #1 test card


    
#=======================================button(s)

rng_button = Button(canvas1, text='Play??', fg='white', bg='black', command=(lambda: shuffle(x)) )
rng_button.grid(row=0, column=2)



#=======================================test 1



if x == [0]:
    #photo2 = PhotoImage(file=image2)  # commented out for below test
    
    print 'Test for RNG sucessful.'

#=======================================run

canvas1.mainloop()

I am stuck at a point where I feel I am missing something that allows for display of this particular image.

Any help or comments would be greatly appreciated

Thank-you in advance.

reRanger

Recommended Answers

All 5 Replies

Vegaseat:

Thank-you for your reply and also the link.

Could you please explain a few things about that code for me? (the below text highlighted in blue is where I am unsure + I have never used Python dictionaries:

  • return [ suit + rank for suit in "CDHS" for rank in "A23456789TJQK" ]
  • image_dict[card] = PhotoImage(file=image_dir+card+".gif")
  • photo1 = PhotoImage(file=image_dir+"C2.gif")

Thank-you for all your help.

reRanger ;)

I will try to answer your question in stages, my internet service is kicking me out all too frequently as of late.

The first function of the card game uses a thing called list comprehension, an efficient way to create a list. Allow me to use php tags to add some color to the code ...

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

You can break down the list comprehension to the more traditional way to create a list ...

# create a list of all card names using a list comprehension
card_list1 = [ suit + rank for suit in "CDHS" for rank in "A23456789TJQK" ]

# a list comprehension is a more efficient way to create a list than
# this traditional nested for loop way ...
card_list2 = []
for suit in "CDHS":
    for rank in "A23456789TJQK":
        # eg. append the concatination of 'C'+'A' = 'CA'
        card_list2.append(suit+rank)

# to test print the first 13 items of each card list ...
print card_list1[:13]  # ['CA', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'CT', 'CJ', 'CQ', 'CK']
print card_list2[:13]  # ['CA', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'CT', 'CJ', 'CQ', 'CK']

You could use either way, but a list comprehension is simply faster. There is a discussion on list comprehension at:
http://www.daniweb.com/code/snippet454.html

You are familiar with a list in Python. A list uses an index of sequential integers (0, 1, 2, ...) to access the items in the list. A dictionary is a bit more advanced, it uses a key to access the value of an item. Dictionary items appear as key:value pairs. Items can be looked up by their key. A key can be a number, a string or any immutable object. It has to be unique!

In the card game this function loads all the images, and puts the image object in as value under the card name key ...

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

The line image_dict[card] = PhotoImage(file=image_dir+card+".gif") generates the key:value pair, or in this case the card_name:image_object pair. Later on we can access the dictionary with the card's name, let's say HK (King of Heart) and the image of that card can be displayed with Tkinter's canvas1.create_image() function.

There is more information on dictionaries at the Python code snippet at:
http://www.daniweb.com/code/snippet192.html

Your last question is contained in this part of the card game code ...

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

As the comments tell, I picked out one of the card image files, C2.gif (the two of club), to get the width and height of the image, so I can set the size of the canvas large enough to show five cards with a little room to spare. Note that photo1 is the image object and for instance photo1.width() returns the width of the image. All the cards are the same size, just like in Las Vegas. We wouldn't want anybody to cheat!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.