Pysimplegui: [question] control text in input boxes

Created on 27 Jan 2019  路  6Comments  路  Source: PySimpleGUI/PySimpleGUI

I want to generate an event in a input box in order to prevent that the user introduce a non numerical character in the text (only numeric values allowed), I can manage to do that. But now I would like to limit the number of characters that you can write, for this I would have to compare the old string with the one that is there when the event is generated. Is not a good idea to give access to the previous input string before the event was generated? Checking the object that generates the event I only see 'default_text' attribute. Actually I dont see where the actual text is (out of values[key])

All 6 comments

PySimpleGUI doesn't save a history of the values that have been previously shown in elements. This is something your application needs to do. Save the value of the input after a read and use it to compare when the next read happens.

I would like to limit the number of characters that you can write

Why can't you simply get the "value" of your input and check the length? If it's "too long" then set the input field to your value minus the last character that was input.

Here's what I mean... this program will only allow 5 characters to be entered into the input field

import PySimpleGUI as sg

layout = [
            [sg.Input(do_not_clear=True, enable_events=True, key='_IN_')],
            [sg.Button('Exit')]
         ]

window = sg.Window('Window Title').Layout(layout)

while True:             # Event Loop
    event, values = window.Read()
    print(event, values)
    if event is None or event == 'Exit':
        break
    if len(values['_IN_']) > 5:
        window.Element('_IN_').Update(values['_IN_'][:-1])

window.Close()

This issue is very close to what I wished to ask: how to limit to only numbers int/float entry?

import PySimpleGUI as sg

layout = [  [sg.Text('My Window')],
            [sg.Input(key='-IN-', enable_events=True)],
            [sg.Button('Go'), sg.Button('Exit')]  ]

window = sg.Window('Window Title', layout)

while True:             # Event Loop
    event, values = window.read()
    if event in (None, 'Exit'):
        break
    if event == '-IN-' and values['-IN-'] and values['-IN-'][-1] not in ('0123456789.'):
        window['-IN-'].update(values['-IN-'][:-1])
window.close()

There ya go....Not sure why this is still open so thanks for flagging it.
[EDIT - Sorry for the edits, I keep making mistakes]

Thank you ! :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ECOM-Klaus picture ECOM-Klaus  路  4Comments

MikeTheWatchGuy picture MikeTheWatchGuy  路  3Comments

MikeTheWatchGuy picture MikeTheWatchGuy  路  6Comments

mozesa picture mozesa  路  5Comments

scmanjarrez picture scmanjarrez  路  5Comments