【发布时间】: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: ''
我发现了许多与该问题相关的主题,但没有一个对我有特别帮助(或至少我理解)。我只是感到困惑,因为有时会发生,有时不会。任何帮助/提示将不胜感激。
背景信息:
Python34
Win7-64 位
我已经这样做了不到一周,请放轻松。
我只提供了我认为需要的代码量。
【问题讨论】:
-
我相信问题是
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