Base 10传递int时出错

时间:2016-05-20 12:21:04

标签: python user-interface tkinter python-3.4

我不断得到的错误是当我试图确定天气时,玩家有足够的猜测留下来继续玩。我无法弄清楚是否有人知道如何解决这个问题请我被卡住了。 我也是python的初学者,我知道还有其他更简单的方法可以做到这一点我只是不知道如何。

这里我收到了我的错误:

 File c:  line 68, in initalize_loop
        total_guesses = int(total_guesses_left.get())
    ValueError: invalid literal for int() with base 10: '[]'

这是我的完整代码:

from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import random
import os
import sys
#Section the Functions are stored.

def loadWordList(words):
    try:
        fin = open(words)       
        for line in fin:
            tmp = fin.readline()
            wordList.append(tmp.rstrip("\n"))   
        fin.close
    except OSError as err:
        print("File Error: ", err, "\n")
        exit(1)

def exity():
    sys.exit()


def getHint(word, guessed_letter):
#Stores the word in characters in which the player cannot see but still gives the ammount of charaters.
    hint = ""
    c = 0
    while ( c <= (len(word) - 1)):
        if word[c] in guessed_letter:
#increments each hint that is correctly guessed unlocking the guessed letter.
            hint += word[c]
            c += 1
        else:
            hint += "_"
            c +=1
    return hint

def countOccurences(word, guess):
    c = 0
    count = 0
    while c <= (len(word)-1):
#Shows the ammount of times the letter occured in that word.
        if guess == word[c]:
            count +=1
            c += 1
        else:
            c += 1
    return count

def get_letter(*args):
    guess = inputted_value.get()
    guess = guess.lower()
    return guess


def valid_guess(guess):
    if guess.isalpha() and 1 == len(guess):
        return True
    else:
        user_help.set(invalid_guess)
    return False

def final_guess(*args):
    finalguess = inputted_value.get()
    finalguess = finalguess.lower()

def initalize_loop(*args):
    total_guesses = int(total_guesses_left.get())
    if ((int(total_guesses > 0)) and (secret_word.get() != word)):
        guess = get_letter()
        valid = valid_guess(guess)
        if valid == True:
            if guess in guessed_letter:
                invalid_input.set("You have already guessed that letter '{}'".format(guess))
            elif guess in word:
                invalid_input.set("That is a good guess! '{}' occurs {} time(s) in the secret word.".format(guess, countOccurences(guess, word)))
            else:
                 invalid_input.set("'{}' does not occur in the secret word.".format(guess))
            guessed_letter.append(guess)
            total_guesses =-1
        word_entry.delete(0, 'end')
        secret_word_value.set(getHint(word, guesses))
        total_guesses_left.set(total_guesses)
        print(guessed_letter)
    else:
        if(secret_word_value.get() == word):
            messagebox.showinfo(title= "Winner!", message=("Congradulations! You Correctly guessed the secret word: {}".format(word)))
            root.destroy()
        else:
            finalguess = final_guess()
            if finalguess == word:
                messagebox.showinfo(frame, title="Congratulations", message= ("Congradulations! You Correctly guessed the secret word: {}".format(word)))
                root.destroy()
            else:
                messagebox.showinfo(title= "Incorrect", message=("Sorry, the secret word was: {} ".format(word)))
                root.destroy()







root = Tk()
root.title('COSC 110 Guessing Game' )
frame = ttk.Frame(root, padding = '4 4 15 15')
frame.grid(column=0, row=0, sticky=(N, W, E, S))

inputted_value = StringVar()
user_help = StringVar()
total_guesses_left = StringVar()
secret_word_value = StringVar()
invalid_input = StringVar()

empty = " "
invalid_guess = "Invalid Guess. Please Enter a letter from A-Z"


word_entry= ttk.Entry(frame, width=7)
word_entry.grid(column=2, row=2, sticky=(W, E))

exit_button= ttk.Button(frame, text='Exit', command=exity)
exit_button.grid(column=1, row =7, sticky=(W))

entered_guess = ttk.Label(frame, text='Enter a Letter')
entered_guess.grid(column=1, row=2, sticky=(W, E))

secret_guess = ttk.Label(frame, textvariable=secret_word_value)
secret_guess.grid(column=2, row=1, sticky=(W, E, N, S))

guesses_label= ttk.Label(frame, text='Guesses Remaining:')
guesses_label.grid(column=1, row=3, sticky=(W, E))

total_guesses = ttk.Label(frame, relief ="sunken", textvariable= total_guesses_left)
total_guesses.grid(column=2, row=3, sticky=(W, E))

user_details = ttk.Label(frame, textvariable = user_help)
user_details.grid(column=1, row = 5, sticky=(W, E))

invalid_guesses = ttk.Label(frame, textvariable = invalid_input)
invalid_guesses.grid(column=1, row = 6, sticky =(W, E))

secret_word = ttk.Label(frame, text='Secret Word:')
secret_word.grid(column=1, row=1, sticky=(W, E))

enter_button = ttk.Button(frame, text='Enter', command = initalize_loop)
enter_button.grid(column=3, row =2, sticky=(W, E))



for child in frame.winfo_children():
    child.grid_configure(padx=5, pady=5)

enter_button.focus()
enter_button.bind('<Return>', initalize_loop)

if __name__ == "__main__":
    if_true = True
    while if_true == True:
        wordList =[]
        loadWordList("Words.txt")
        word = random.choice(wordList)
        guessed_letter = []
        total_guesses = 10

        secret_word_value.set(getHint(word, guessed_letter))
        total_guesses_left.set(guessed_letter)
        invalid_input.set(empty)
        user_help.set(empty)

        root.mainloop()
        if_true = messagebox.askyesno(icon="question", title= "Play Again?", message ="Would you like to play again?")
    exit(0)

2 个答案:

答案 0 :(得分:1)

首先在这里初始化变量:

total_guesses_left = StringVar()

然后,在if __name__ == "__main__":内写下:

    guessed_letter = []
    // ...
    total_guesses_left.set(guessed_letter)

因此,我们存储为StringVar的{​​{1}}实例将其值设置为空列表。因为它是total_guesses_left,这会导致转化,这意味着它的内部值现在是字符串“StringVar”。

然后在[]中,您尝试

initalize_loop

当然 total_guesses = int(total_guesses_left.get()) 会返回一个字符串,或者更确切地说,它会返回字符串“total_guesses_left.get()”。

[]解析表示具有特定基数(默认为10)的数字的字符串时,它只能处理由字母数字字符组成的字符串,并且只有当它们只包含指定数字基数使用的字符时(即默认只有字符int)。

因此,您会收到“0123456789”无法解析为[]的异常。

您可能希望int存储有效的整数表示字符串而不是列表中的一个。

答案 1 :(得分:-1)

这意味着在那一刻你的total_guesses_left.get()正在给'[]'。当您尝试转换char或类似

之类的字符串之外的其他内容时,会出现base 10错误
    >>> str1='a'
    >>> int(str1)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: 'a'
    >>> alist='[]'
    >>> int(alist)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: '[]'

我希望你理解错误。玩错了一点。 “试验和错误”:D