这是我要在条目小于1000时显示错误消息的代码,一切看起来都很好,但是当我运行此代码时,我得到了我在底部提到的错误,这是您需要查看的所有内容< / p>
import tkinter as tk
from tkinter import ttk
from tkinter.constants import *
from tkinter import messagebox
root=tk.Tk()
root.title("Date converter")
gy=tk.IntVar()
jy=tk.IntVar()
def cj():
if jy.get() <1000 :
messagebox.showerror("ERROR", "Entry of year must be upper than oneThousand (1000) !")
else:
Answerj.configure(text=jy.get())
def cg():
if gy.get()<1000:
messagebox.showerror("ERROR", "Entry of year must be upper than oneThousand (1000) !")
else:
Answerg.configure(text=gy.get())
def justint(inStr,acttyp):
if acttyp == '1':
if not inStr.isdigit():
return False
return True
entryjy=ttk.Entry(root , width=6 , validate="key", textvariable=jy)
entryjy['validatecommand'] = (entryjy.register(justint),'%P','%d')
entryjy.delete(0, END)
entryjy.grid(row=0 , column=0)
entrygy=ttk.Entry(root , width=6 , validate="key", textvariable=gy)
entrygy['validatecommand'] = (entrygy.register(justint),'%P','%d')
entrygy.delete(0, END)
entrygy.grid(row=1 , column=0)
Answerj=ttk.Button(root,text=" ",state=DISABLED,style='my.TButton')
Answerj.grid(row=0,column=2)
Answerg=ttk.Button(root,text=" ",state=DISABLED,width=10,style='my.TButton')
Answerg.grid(row=1,column=2 )
buttong=ttk.Button(root,text="calculate",command=cg,width=10,style='my.TButton')
buttong.grid(column=1,row=0)
buttonj=ttk.Button(root,text="calculate",command=cj,style='my.TButton')
buttonj.grid(column=1,row=1)
root.mainloop()
不幸的是,这是我得到的错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Hadi\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 505, in get
return self._tk.getint(value)
_tkinter.TclError: expected integer but got ""
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Hadi\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1702, in call
return self.func(*args)
File "D:\python\soal_az_stack.py", line 20, in cg
if gy.get()<1000:
File "C:\Users\Hadi\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 507, in get
return int(self._tk.getdouble(value))
_tkinter.TclError: expected floating-point number but got ""
如果您能说出问题出在哪里,我将非常有义务!
答案 0 :(得分:1)
您需要首先验证该字段包含有效数字而不是空字符串。
处理此问题的一种方法是使用try/except
语句,该语句将尝试您的函数,如果失败,则会让您知道一些错误消息。
将cj()
和cg()
更改为此:
def cj():
try:
if jy.get() < 1000:
messagebox.showerror("ERROR", "Entry of year must be upper than oneThousand (1000) !")
else:
Answerj.configure(text=jy.get())
except:
messagebox.showerror("ERROR", "Entry field does not contain a valid number!")
def cg():
try:
if gy.get() < 1000:
messagebox.showerror("ERROR", "Entry of year must be upper than oneThousand (1000) !")
else:
Answerg.configure(text=gy.get())
except:
messagebox.showerror("ERROR", "Entry field does not contain a valid number!")