如果条目的输入定义为IntVar,而我们在输入框中输入的不是IntVar(如string),则产生错误消息
下面是我编写的代码:nobad_sign = tk.IntVar()
nohp_sign = tk.IntVar()
nobad_entry_sign = tk.Entry(frm2, textvariable=nobad_sign,width= 20,
font=('verdana',13))
nobad_entry_sign.pack(pady=(10,20), anchor='w')
nohp_entry_sign = tk.Entry(frm2, textvariable=nohp_sign,width= 20,
font=('verdana',13))
nohp_entry_sign.pack(pady=(10,20), anchor='w')
def submit():
if nobad_sign.get() == "" or noph_sign.get() == "":
msg.showerror('Visitor Data', 'please input with number')
submit_btn = tk.Button(frm2, text='Submit', bg='gray25', fg='alice blue',
font=('Britannic Bold',12), width=20, relief=tk.GROOVE,
borderwidth=4, command=submit)
submit_btn.pack(pady=(10,10), anchor='w')
出现的错误语法是:
Traceback (most recent call last):
File "C:UsersHP-PCAppDataLocalProgramsPythonPython310libtkinter__init__.py", line 570, in get
return self._tk.getint(value)
_tkinter.TclError: expected integer but got ""
你能帮我解决这个问题吗?
我想让错误信息在条目为空白时弹出"或输入stringVar
正如评论中提到的,您可以对Entry小部件的每个文本变量使用StringVar
而不是IntVar
。初始值可设置为"0
"。然后,在submit
函数中,您可以使用字符串方法来确保输入是一个数字,而不仅仅是检查空字符串"。
例如:
from tkinter import *
import tkinter as tk
import tkinter.messagebox as msg
frm2 = Tk()
nobad_sign = tk.StringVar()
noph_sign = tk.StringVar()
nobad_sign.set("0")
noph_sign.set("0")
nobad_entry_sign = tk.Entry(frm2, textvariable=nobad_sign,width= 20,
font=('verdana',13))
nobad_entry_sign.pack(pady=(10,20), anchor='w')
nohp_entry_sign = tk.Entry(frm2, textvariable=noph_sign,width= 20,
font=('verdana',13))
nohp_entry_sign.pack(pady=(10,20), anchor='w')
def submit():
values = [nobad_sign.get(), noph_sign.get()]
if not all(val.isdigit() for val in values):
msg.showerror('Visitor Data', 'please input with number')
submit_btn = tk.Button(frm2, text='Submit', bg='gray25', fg='alice blue',
font=('Britannic Bold',12), width=20, relief=tk.GROOVE,
borderwidth=4, command=submit)
submit_btn.pack(pady=(10,10), anchor='w')
frm2.mainloop()