不知道我为什么会得到" ValueError:对于带有base10的int()的无效文字:'' "

时间:2015-12-12 04:59:18

标签: python python-3.x tkinter

window = tk. Tk()  #creates a new window
age = StringVar()
window.title("Are you old enough to smoke?")  #title
window.geometry("300x200")  #window size
window.wm_iconbitmap('favicon.ico')  #icon

photo = tk.PhotoImage(file="images.png")  #picture in said window
w = tk.Label(window, image=photo)
w.pack()

lbl=tk.Label(window, text="Please enter your age.", bg="light salmon", fg="blue2")  #label text & color
lbl.pack()

ent = tk.Entry(window, text="(Your age here)", textvariable=age)
ent.pack()


def callback():
    ageint = int(age.get())
#Line causing error RIP^
    if ageint >= 18:
        mess = 'You are legally able to smoke cigarettes.'
    elif ageint <= 12:
        mess = "You're to young to smoke,\nGet out of here."
    else:
        mess = "You are not of legal age to smoke."

    if ageint >= 21:
        mess += "\nYou are legally able to smoke marijuana."
    if ageint >= 40:
        mess += "\nYou're above the age of forty,\nDo you really need to ask 

    messagebox.showinfo(title="Can you Smoke", message=mess)

btn = tk.Button(window, text="Confirm", bg="sienna1", fg="blue2", relief="groove", command=callback)
btn.pack()

有我的代码。当我运行我的程序(非常简单的小练习)时,每件事都很有效,它有时会工作并显示正确的信息。但有时我的消息框没有显示,并且控制台中出现此错误:

Exception in Tkinter callback
    Traceback (most recent call last):
      File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
        return self.func(*args)
      File "C:/Users/Josh/Documents/Trial Python Programs/Smoke window Program.py", line 22, in callback
        ageint = int(age.get(), base=3)
    ValueError: invalid literal for int() with base 10: ''

我找到了很多与这个问题有关的话题,但没有一个特别有助于我(或至少我理解)。我只是感到困惑,因为有时它会发生,有时则不会。任何帮助/提示将不胜感激。

背景资料:

  1. Python34

  2. Win7-64位

  3. 我已经这样做了不到一个星期了,请放轻松。

  4. 我只提供了我认为需要的代码量。

2 个答案:

答案 0 :(得分:2)

正如@tdelaney在评论中所说,错误消息显示StringVar age为空。

在尝试将其转换为int之前,您可以测试该年龄包含int表示(通过正则表达式)

import re
intre = re.compile("\d+")
...
if intre.match(age.get):
    ageint = int(age.get())
    ...
else:
    # warn the user for invalid input

你也可以使用乐观方式:它应该是好的,只是测试异常条件

...
try:
    ageint = int(age.get())
except ValueError:
    # warn the user for invalid input

在这种情况下,您最好直接使用IntVar年龄:

age = IntVar()
...
try:
    ageint = age.get()
...

但是,如果您想确保用户只能在Entry中输入数字,则应使用validatevalidatecommand选项。不幸的是,他们在Tkinter世界中的记录很少,我能找到的最佳参考是其他2个SO帖子,herehere

答案 1 :(得分:1)

这可以使您的程序更稳定:

def callback():
    try:
        ageint = int(float(age.get()))
    except ValuError:
        mess = "Please enter a valid number."
        messagebox.showinfo(title="Invalid Input", message=mess)
        return
    if ageint >= 18:
    # rest of your code