简体   繁体   中英

Python - Tkinter: error saying my index is out of range, when there is

So, I am making this hangman game for a school project, and have come across a problem, that I just cannot for the life of me figure out even why it happens.

word_list = ["APPLE", "PEAR", "BANNANA"]

word = word_list [random.randint(0,2)]

hidden_word = ["_ " * len(word)]
print (word)

This bit of code is a list, and then one of the words made into a string variable:

word = word_list [random.randint(0,2)]

I then make a new list that is the hidden word, with '_' used to hide, by getting the length:

hidden_word = ["_ " * len(word)]

I then print the word (for development)

print (word)

On to the problematic code.

def click_1 (key):
    if str(key) in word:
        key_1 = word.index(key)
        print (key_1)
        hidden_word[key_1] = key
        print (hidden_word)
    else:
        print ("Nope")
    return letter

r = c = 0
for letter in string.ascii_uppercase:
    Button(letter_frame, text=letter, command=functools.partial(click_1, letter)).grid(row=r, column=c, sticky=W)
    c += 1
    if c > 12:
        c = 0
        r += 1

This makes butons come up, and when I click on the button with the letter, it checks if it's in the word, and then (at the moment) prints:

BANNANA
>>> 0
['B']

if the word is bannana. The problem is when I press the A:

1

comes up, and if I press something else, this error appears:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/idlelib/run.py", line 121, in main
    seq, request = rpc.request_queue.get(block=True, timeout=0.05)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/queue.py", line 175, in get
    raise Empty
queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/tkinter/__init__.py", line 1475, in __call__
    return self.func(*args)
  File "/Users/alexeacott/Desktop/Hangman.py", line 24, in click_1
    hidden_word[key_1] = key
IndexError: list assignment index out of range

The last line is of most intersest, because apparantly, N is out of range. My question is, why is this happening, and what could I do to fix.

Happy Holidays!

The following line make a list with a single element (the elemnt is a string with word-length long "_ _ _ ..." string):

hidden_word = ["_ " * len(word)]

Accessing the element (index > 0) cause the IndexError because there is only one element in the list.

You may be wanted to create a list of multiple element:

hidden_word = ["_ "] * len(word)

>>> ["_ " * 3]
['_ _ _ ']
>>> ["_ "] * 3
['_ ', '_ ', '_ ']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM