简体   繁体   中英

Bind enter key in python

I am currently writing a tui app using picotui and python. I am trying to create a user input box on my form using the 'WTextEntry' widget, but I can't work out how to get the data from the box when I press enter. What is the best way to bind the enter key (ideally without external libraries) so it runs like this:

e = WTextEntry(100, "")
d.add(22, 40, e)
if("enter key is pressed"):
     e.get()

Any help with this would be appreciated.

The widgets and editors from picotui support signals and signal handlers. That means that it's possible to handle a user-triggered event, like hitting the key enter.

# I'm assuming you already have a dialog at this point

def handle_enter(w):
    print(w)

e = WTextEntry(100, "")
d.add(22, 40, e)

e.on("enter", handle_enter)

The most important precondition is that the code is running inside the main loop. The code you write must run inside an infinite loop, which draws the widgets and collects user inputs. Without such an infinite loop, your code finishes right after drawing everything and you don't get the change to handle the signals. The library provides the main loop, you need to make sure to run it.

def handle_enter(w):
    print(w)

e = WTextEntry(100, "")
d.add(22, 40, e)

e.on("enter", handle_enter)

res = d.loop()

The method d.loop() is what starts the infinite main loop and allows you to handle the events.

EDIT: Even though the remarks in the original answer are correct, it seems that the widget WTextEntry doesn't support the signal enter . This is visible from the source code as handling of the KEY_ENTER key is skipped.

It seems the solution is to create a button and handle its signal click . Within the signal handler for the button, it's possible to process the text entry as well.

Here is a short example:

from picotui.context import Context
from picotui.screen import Screen
from picotui.widgets import *


def handle_click(w):
    with open('test.txt', 'w') as f:
        f.write(e.t)


with Context():

    d = Dialog(5, 5, 50, 12)

    d.add(1, 1, "Entry:")

    e = WTextEntry(100, "Text")
    d.add(10, 1, e)

    b = WButton(10, "Click")
    d.add(10, 10, b)
    b.on("click", handle_click)

    res = d.loop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM