# 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) # 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, currentWord): # Letter is used redrawWord() else: # A miss occured # Nothing to do yet print "LETTER WAS A MISS!" # Check if a letter has already been guessed def isLetterUsed(letter, currentWord): for index in range(len(currentWord)): print index print currentWord[index] 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('