You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制Gtk.Entry仅允许输入数字(GTK 4 + Python)

在GTK 4的Python开发中限制Gtk.Entry仅输入数字

要实现Gtk.Entry仅允许输入数字字符,核心思路是拦截文本插入信号,过滤掉非数字内容。具体可以通过监听insert_text信号来实现,以下是完整的代码示例和关键说明:

完整实现代码

import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk

class NumberEntryWindow(Gtk.ApplicationWindow):
    def __init__(self, app):
        super().__init__(application=app, title="仅允许数字输入")
        self.set_default_size(300, 100)

        # 创建目标Entry组件
        self.entry = Gtk.Entry()
        self.entry.set_placeholder_text("请输入数字")
        # 绑定insert_text信号到自定义处理函数
        self.entry.connect("insert-text", self.on_insert_text)

        # 布局容器
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        box.set_margin_top(20)
        box.set_margin_start(20)
        box.set_margin_end(20)
        box.append(self.entry)
        self.set_child(box)

    def on_insert_text(self, entry, text, length, position):
        # 只保留输入文本中的数字字符
        filtered_text = ''.join([char for char in text if char.isdigit()])
        if filtered_text:
            # 若存在合法数字,调用GTK默认的插入逻辑
            entry.do_insert_text(entry, filtered_text, len(filtered_text), position)
        # 返回True阻止GTK执行默认的插入行为(避免非数字内容被插入)
        return True

class NumberEntryApp(Gtk.Application):
    def __init__(self):
        super().__init__(application_id="org.example.NumberEntry")

    def do_activate(self):
        win = NumberEntryWindow(self)
        win.present()

if __name__ == "__main__":
    app = NumberEntryApp()
    app.run(None)

关键细节说明

  • 信号拦截:insert_text信号会在文本即将插入到Entry时触发,我们可以在回调函数中控制是否允许插入内容。
  • 字符过滤:通过列表推导式筛选出输入文本中的数字字符,仅保留合法内容。
  • 手动触发插入:如果存在合法的数字字符,调用entry.do_insert_text()执行插入操作;如果没有合法内容,直接返回True阻止默认插入逻辑。

如果需要支持小数点、负号等特殊数字格式,可以修改过滤条件,例如:

# 支持小数点(注意需额外处理重复小数点的情况)
filtered_text = ''.join([char for char in text if char.isdigit() or char == '.'])

内容的提问来源于stack exchange,提问作者Fred

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:42:12