如何修复python的ValueError?

时间:2018-07-31 06:20:19

标签: python tkinter

点击“开始”按钮后,代码产生了ValueError:

“ clicked4”中第58行的文件“ E:\ python \ number猜测trial2.py”

run_game()

run_game中的文件“ E:\ python \ number猜测trial2.py”,第61行

guess = int(guess_entry.get())

ValueError:以10为底的int()无效文字:

有人可以向我解释为什么会产生ValueError吗?

#Import tkinter module and random from tkinter module
from tkinter import *
import random
import time

win = Tk()
win.configure(cursor='gumby', bg='yellow')
win.title('A sImPlE gUeSsInG gAmE')
win.wm_iconbitmap('favicon.ico')
number = random.randint(1, 101) #set number as a random integer
f = Frame(win)
#No play button(NO)
def clicked():
    win.destroy()

#Play button (YES)


def clicked1():
    #Erase previous screen
    l.destroy()
    l2.destroy()
    NO.destroy()
    YES.destroy()

    win.title('Are you READY?')
    win.wm_iconbitmap('favicon.ico')
    win.configure(background = "deep sky blue", cursor='rtl_logo')
    f2 = Frame(win)    
    l3.grid(row = 1, column = 4, columnspan=5)

    #'Next' button
    NEXT.grid(row = 5, column = 6)

#NEXT button command
def clicked2():
    win.title('Are you READY?')
    win.wm_iconbitmap('favicon.ico')
    win.configure(background = "deep sky blue", cursor='rtl_logo')
    f3 = Frame(win)
    l3.destroy()
    NEXT.destroy()   
    l4.grid(row = 1, column = 3, columnspan=5)    
    NEXT2.grid(row = 4, column = 5)

#Ready to begin screen
def clicked3():
    win.title('READY?')
    l4.destroy()
    NEXT2.destroy()
    l5.grid(row = 1, column = 3, columnspan=6)
    BEGIN.grid(row = 3, column = 6)

#START button's command
def clicked4():
    l5.destroy()
    BEGIN.destroy()
    run_game()
    #Submit button's command
def run_game():
    guess = int(guess_entry.get())
    if guess != number:
             print_text = "you guessed {0}.".format(guess)

    if guess > number:
            print_text = ("That's too high. Guess lower...")
    elif guess < number:
            print_text = ("That's too low. Guess higher...")

            win.text.delete(0.0, END)
            win.text.insert(0.0, print_text)

            guess_entry.delete(0, END)
    else:
           print_text = ("That's the right number! Well done!")
           win.text.delete(0.0, END)
           win.text.insert(0.0, print_text)
           start_again()

    L2.grid(row=1, column=1)

    #Guess box label
    L1.grid(row=2, column=1)

    #Guess box / add entry box for typing guess
    guess_entry.grid(row=2, column=4)

    #Submit button
    submit.grid(row = 3, column = 4)


    # create computer feedback text box
    win.text.grid(row = 20, column = 0, columnspan = 5)

#'START AGAIN?' SCREEN
def start_again():
    L2.destroy()
    L1.destroy()
    guess_entry.destroy()
    submit.destroy()
    win.text.destroy()
    AGAIN = Label(win, text = 'Start Again?', bg = 'deep sky blue', fg = 'yellow', font=('Snap ITC', 30)) 

#Intro
l = Label(win, text = "Welcome to a number game child.", font=('Snap ITC', 30), bg='yellow', fg='slateblue')
l2 = Label(win, text = "Would you like to play?", font=('Snap ITC', 30), bg = 'yellow', fg='slateblue')
l.grid(row = 1, column = 3, columnspan=5)
l2.grid(row = 2, column = 3, columnspan=5)

#Play or not buttons(YES/NO)
NO = Button(win, text = 'NO', command=clicked, relief=RAISED, padx=30, pady=1 )
NO.config(bg='DodgerBlue2', fg='spring green', font=('Snap ITC', 10), bd=6)
NO.grid(row = 4, column = 4)
YES = Button(win, text = 'YES', command=clicked1, relief=RAISED, padx=30, pady=1)
YES.config(bg='DodgerBlue2', fg='spring green', font=('Snap ITC', 10), bd=6)
YES.grid(row = 4, column = 6)

#SCREEN 2
l3 = Label(win, text = 'The rule is simple. You have 5 chances to \n guess what number I am thinking of.', bg = 'deep sky blue', fg = 'yellow', font=('Snap ITC', 30))
NEXT = Button(win, text = 'NEXT', command=clicked2, bd=6,relief=RAISED, bg = 'firebrick1', fg='DarkOrchid1', padx=30, pady=1, font=('Snap ITC', 10))

#SCREEN 3
l4 = Label(win, text = 'I am thinking of a number between 1 to 100.\n Good Luck!', bg = 'deep sky blue', fg = 'yellow', font=('Snap ITC', 20))
NEXT2 = Button(win, text ='NEXT', command=clicked3, bd=6, relief=RAISED, bg = 'firebrick1', fg='DarkOrchid1', padx=30, pady=1, font=('Snap ITC', 10 ))

#SCREEN 4
l5 = Label(win, text = "Are You Ready?", bg = 'deep sky blue', fg = 'yellow', font=('Snap ITC', 30))
BEGIN = Button(win, text = 'BEGIN', command=clicked4, bd=6, relief=RAISED, bg = 'firebrick1', fg='DarkOrchid1', padx=30, pady=1, font=('Snap ITC', 10))

#SCREEN 5
L2 = Label(win, text = 'A Number Guessing Game', bg='yellow', fg='slateblue', underline=1, font=('Papyrus', 18))
L1 = Label(win, text = 'Make your guess here ----->', bg='yellow', fg='slateblue', font=('Papyrus', 18))
guess_entry = Entry(win, bg = 'turquoise', fg = 'magenta2', cursor = 'pencil')
submit = Button(win, text = "OK", command = run_game, bg = 'purple', fg = 'yellow')
win.text = Text(win, width = 35, height = 1, bg='slateblue', fg='springgreen2')

3 个答案:

答案 0 :(得分:1)

在给用户机会在输入框中键入任何内容之前,请致电guess_entry.get()。因此,输入框为空,因此guess_entry.get()返回一个空字符串,该字符串不能转换为整数。

最简单的方法是将run_game函数拆分为首次设置游戏的函数和处理每个猜测的函数。我还修复了您的run_game函数中的一些缩进错误,并确定了另外两个问题,我已对此进行了评论。请注意,如果用户键入任何无法转换为整数的内容,这仍将提供相同的ValueError。您可以使用try-catch块或使用entry validation来解决。

def clicked4():
    l5.destroy()
    BEGIN.destroy()
    init_game()

def init_game():
    L2.grid(row=1, column=1)
    #Guess box label
    L1.grid(row=2, column=1)
    #Guess box / add entry box for typing guess
    guess_entry.grid(row=2, column=4)
    #Submit button
    submit.grid(row = 3, column = 4)
    # create computer feedback text box
    win.text.grid(row = 20, column = 0, columnspan = 5)

def run_game():
    guess = int(guess_entry.get())
    if guess != number:
        print_text = "you guessed {0}.".format(guess) # This does nothing, you always overwrite it.

        if guess > number:
            print_text = ("That's too high. Guess lower...")
        elif guess < number:
            print_text = ("That's too low. Guess higher...")

        win.text.delete(0.0, END)
        win.text.insert(0.0, print_text)
        guess_entry.delete(0, END)
    else:
       print_text = ("That's the right number! Well done!")
       win.text.delete(0.0, END)
       win.text.insert(0.0, print_text)
       start_again() # This fires immediately, so you will never see the message

答案 1 :(得分:0)

您是否尝试调试代码? 尝试打印guess_entry.get(),看看该值是否为整数。 可能是编译器没有将值解析为整数。 您可以使用try-except来处理ValueError异常。

答案 2 :(得分:0)

我插入了这一行      打印“ --->'”,guess_entry.get(),“'”  就在您的行之前      guess = int(guess_entry.get())

我得到 --->''

因此,看来您的guess_entry.get()的值是空格 可以解释您的错误。