【问题标题】:No idea why I am getting "ValueError: invalid literal for int() with base10: '' "不知道为什么我会收到“ValueError: invalid literal for int() with base10: ''”
【发布时间】:2015-12-12 04:59:17
【问题描述】:
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. 我只提供了我认为需要的代码量。

【问题讨论】:

  • 我相信问题是int(age.get()) 如果它得到一个小数,它会给出你得到的同样的错误
  • 如果您在条目中输入小数,它不应该是正常数字吗?就像如果我输入 18.5,它不会只是将其视为 18 和 19 之间的一半吗? (这只是我头脑中的逻辑,与代码如何工作的实际知识无关)。如果没有,有没有办法让它这样做?我也不明白为什么有时你输入一个整数时它仍然会发生。
  • 您可以尝试将int() 更改为float() 看看是否可行
  • 当我发布时,我再次遇到错误。这次它说 ValueError: could not convert string to float:
  • 错误信息给你一个很好的提示:ValueError: invalid literal for int() with base 10: ''。末尾的那些空引号是您尝试转换为 int 的空字符串。因此,您的程序运行正常,它只是捕获了用户的错误输入(在这种情况下,没有输入任何数据)。捕获异常并显示“尝试按照说明操作”消息框。

标签: python python-3.x tkinter


【解决方案1】:

正如@tdelaney 在其评论中所说,错误消息说StringVar age 是空的。

您可以在尝试将其转换为 int 之前测试 age 是否包含 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

【讨论】:

    【解决方案2】:

    这可以让你的程序更稳定:

    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
    

    【讨论】:

      猜你喜欢
      • 2018-02-01
      • 1970-01-01
      • 2018-05-07
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2022-08-01
      • 2022-01-09
      相关资源
      最近更新 更多