I am using GTK 4 with Python and have a Gtk.Entry
widget which I would like to limit the characters which can be entered to numbers only. How do I do that?
Asked
Active
Viewed 18 times
1 Answers
0
You could connect the changed
signal of teh Gtk.Entry
to a callback function. In the call back function check the content of the input and remove ny non-numeric chars
def on_entry_changed(self, entry):
# Use GLib.idle_add to delay the action until the main loop is idle
GLib.idle_add(filter_entry_text, entry)
def filter_entry_text(entry):
text = entry.get_text()
new_text = ''.join([char for char in text if char.isdigit()])
if new_text != text:
entry.set_text(new_text)
entry.set_position(-1)
return False

Yoss
- 428
- 6
- 16
-
Thanks, this kind of works, but I get warnings that "Cannot begin irreversible action while in user action", and it also moves the cursor to the beginning. – Fred Aug 24 '23 at 21:37
-
I updated the snipped so the cursor is on put on the end, and also I'm using GLib so that the text is added to the entry when the main loop is iddle. This would prevent the warnings. – Yoss Aug 24 '23 at 21:50
-
Moving the cursor to the end is not ideal since it makes it difficult to edit text in between numbers. But perhaps Gtk is shitty and your answer is "good enough". – Fred Aug 31 '23 at 11:33