Search code examples
pythontkinterwidgettkinter-entry

Checking for numeric inputs in a Entry Widget Tkinter


I have a couple of questions 1) I am trying to get an Entry widget to be restricted to numeric input only. I have seen some samples on stack overflow but they tend to use the class based Tkinter coding and I am doing it usual style.

E=Entry(t3, bg='gray', textvariable=weekly_savings[num], validate='focus', validatecommand=MoneyValidation))
I am not sure how to implement this money validation. The window code is as follows
t3=Toplevel(root)
bg='gold'
t3.title(u"\u092c\u0939\u0940 \u0916\u0924\u093e")
t3.geometry('800x450+100+50')
t3.transient(root)
t3.configure(background=bg)
t3.overrideredirect(True)

Secondly I am working with a semi-literate population for my final use case and we would like to use only the accountants keyboard. I would like to bind the focus shifting to a num lock key. How do I do that?


Solution

  • If your goal is to allow only numerals to appear in the Entry widget, you can use the method detailed by Bryan Oakley in this answer:

    def MoneyValidation(S):
        if S in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
            return True
        t3.bell() # .bell() plays that ding sound telling you there was invalid input
        return False
    
    vcmd = (t3.register(MoneyValidation), '%S')
    E = Entry(t3, bg='gray', validate='key', vcmd=vcmd)
    E.pack()