• tkinter: key binding in a text field

    From Stefan Ram@21:1/5 to All on Tue Oct 18 21:18:03 2022
    I'd like to read text from a text field when the user
    presses "p". After this, the text field should be empty.

    import tkinter

    text = tkinter.Text( None, height=5 )

    def procedure( event ):
    print( repr( text.get( "1.0", "end-1c" )))
    text.delete( "1.0", tkinter.END )

    def cleanup( event ):
    # delete the "p" just inserted
    text.delete( "1.0", tkinter.END )

    text.bind( "<p>", procedure )
    text.bind( "<KeyRelease-p>", cleanup )

    text.pack()
    tkinter.mainloop()

    I had to add a key binding for <KeyRelease-p> to delete
    a "p" that is inserted into the text field.

    The insertation of a "p" is the default behavior
    for the key <p>. I get my "procedure" executed plus
    the default behavior when <p> is pressed and released.

    Is there a way to replace or suppress the default behavior
    for the key <p>, so that I just get my procedure executed
    when <p> is pressed and released but not the default behavior?
    I do not want a "p" to be inserted when <p> is pressed.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Stefan Ram@21:1/5 to Stefan Ram on Tue Oct 18 21:35:54 2022
    ram@zedat.fu-berlin.de (Stefan Ram) writes:
    def procedure( event ):
    print( repr( text.get( "1.0", "end-1c" )))
    text.delete( "1.0", tkinter.END )

    Found it: I need to return "break" from my procedure!

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)