pythontkinterintegertkinter-buttontkmessagebox

How to solve this msg.showerror problem in python tkinter?


I want to make an error message if the input of an entry is defined IntVar and we input not an IntVar such as string to the entry box.

here is the code that I made:

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')

and the error syntax that comes out is:

Traceback (most recent call last):
  File "C:\Users\HP-PC\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 570, in get
    return self._tk.getint(value)
_tkinter.TclError: expected integer but got ""

Can you help me how to solve this?

I want to make that error message pops up when the entry is just blank "" or inputed stringVar


Solution

  • As mentioned in the comments, you can use a StringVar instead of an IntVar for each of the textvariables of the Entry widgets. You can set their initial values to 0. Then in your submit function instead of just checking for an empty string "", you can instead use the string methods to ensure that the input is a number.

    For example:

    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()