# Graphical Version of Hangman # Added in the changeable label # Had to maintain the state of all lettersGuessed and # update the label appropriately from Tkinter import * # Global for the word we're trying to solve currentWord = "POTATO" lettersGuessed=[] # The list of letters that have been guessed wordStr = None # Holds the string being shown to the user (hidden) misses = 0 # How many misses do we have so far? canvas=None # Holds the canvas we're drawing the hangman on images = ['head.gif', 'torso.gif', 'arm1.gif', 'arm2.gif', 'leg1.gif', 'fulldan.gif'] def addPiece(misses): global canvas print "misses is ", misses img = PhotoImage(file=images[misses]) canvas.create_image(0, 6,anchor=NW, image=img) canvas.image = img # Create the canvas and draw the noose def initHangman(parent): global canvas canvas = Canvas(parent, width=300,height=700) canvas.create_line(5,540,220,540) #base canvas.create_line(210, 540, 210, 5) # Long pole canvas.create_line(100, 5, 210, 5) canvas.create_line(100, 5, 100, 10) canvas.pack() # Redraw the word on the screen def redrawWord(): # Start with an empty string and build up the # letters for the word strToDisplay = "" # Go through all characters in the current word for ch in currentWord: if ch in lettersGuessed: # Letter has been guessed strToDisplay += ch else: # Letter has not been guessed strToDisplay += '_' strToDisplay += ' ' # Add a space wordStr.set(strToDisplay) # Handle a user's guess of letter. Check if the guess is correct # and do the appropriate action. # Also, maintain the list of lettersGuessed because we need to know # it later def handleLetter(letter): global misses lettersGuessed.append(letter) if isLetterUsed(letter): # Letter is used redrawWord() else: # A miss occured addPiece(misses) misses = misses + 1 # Check if we have missed to many! if misses >= len(images): print "You lost! End the game here by destroying root or resetting to a new word" # Check if a letter is in the word or not def isLetterUsed(letter): print "DEBUG CW:", currentWord for index in range(len(currentWord)): if letter == currentWord[index]: return True return False # Init Label widget holding the word def initWord(parent): global wordStr wordStr = StringVar() # We need a StringVar since we're going to be changing it wordStr.set("_ "*len(currentWord)) # Set it to all blanks _ lbl = Label(parent, textvariable=wordStr) # Create the label lbl.pack() # Pack it in! def letterPushed(event): b = event.widget letter = b.cget("text") # Get the configuration item named "text" handleLetter(letter) b.config(state=DISABLED) def createButtons(parent): letterFrame = Frame(parent) letterFrame.pack() # Create all the buttons for i in range(26): currentChar = chr(i+65) print currentChar b = Button(letterFrame, text=currentChar, padx=20) b.bind('