[Python] Only allow numbers and "."-input in Entries [duplicate]

Discussão em 'Python' iniciado por Stack, Junho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I only want to input numbers from 0-9 and a "." if I want to input a float number. So far I have this:

    def keylistener(event):
    ACCEPTED = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."]
    if not event.char in ACCEPTED:
    pass
    # Dont let the character be inputed
    #....

    tk.bind('<KeyPress>', keylistener)


    can anyone help me?

    EDIT: maybe there is another problem in my Program, so I extracted the relevant code and post it here now as the complete Python-file

    from tkinter import *

    tk = Tk()
    tk.title("Only Numbers")
    tk.configure(bg="black")
    tk_frame = Frame(relief=RAISED,bd=8,bg="gray")
    category = StringVar(tk_frame)

    def keylistener(event):
    ACCEPTED = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."]
    if event.char not in ACCEPTED:
    return "break"
    # Dont let the character be inputed

    entry = Entry(tk_frame,bg="white",fg="black")

    tk_frame.grid()
    entry.grid(column=1, row=1)

    # Start Keylistener
    tk.bind('<KeyPress>', keylistener)

    tk.mainloop()

    Continue reading...

Compartilhe esta Página