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

Python3/GTK3 Notebook切换标签时如何取消TextEntry焦点避免文本全选

解决思路

该问题是switch-page信号触发时GTK内部尚未完成新页面的焦点分配流程,回调内直接修改焦点的操作会被后续内部逻辑覆盖,因此直接调用焦点相关方法无效。以下是两种可行的解决方案:

方案1:延迟处理焦点逻辑

通过GLib.idle_add将焦点调整逻辑放入GTK主循环的空闲任务队列,等待内部页面渲染、焦点分配完成后再执行,即可生效:

#!/usr/bin/env python3
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib

def addPageToNotebook(notebook, text):
    box = Gtk.Box()
    box.pack_start(Gtk.Label.new(f"Label {text}"), False, False, 0)

    textEntry = Gtk.Entry()
    textEntry.set_text(text)
    box.pack_start(textEntry, True, True, 0)

    button = Gtk.Button.new_with_label(f"Button{text}")
    box.pack_start(button, False, False, 0)

    notebook.append_page(box, Gtk.Label.new(f"Tab {text}"))
    return textEntry, button

def onSwitchPage(notebook, page, pageNumber, textEntry1, button1, textEntry2, button2):
    def adjust_focus():
        # 可根据需求选择调整逻辑:
        # 1. 将默认焦点切换到按钮
        if pageNumber == 0:
            button1.grab_focus()
        else:
            button2.grab_focus()
        
        # 2. 若需要Entry获得焦点但不选中文本,替换为以下代码
        # if pageNumber == 0:
        #     textEntry1.grab_focus_without_selecting()
        # else:
        #     textEntry2.grab_focus_without_selecting()
        return False
    GLib.idle_add(adjust_focus)

notebook = Gtk.Notebook()
textEntry1, button1 = addPageToNotebook(notebook, "1")
textEntry2, button2 = addPageToNotebook(notebook, "2")
notebook.connect("switch-page", onSwitchPage, textEntry1, button1, textEntry2, button2)

window = Gtk.Window()
window.connect("destroy", Gtk.main_quit)
window.add(notebook)
window.show_all()
Gtk.main()

方案2:拦截Entry焦点事件取消选中

若不需要修改默认焦点链,仅要避免切换页面时自动全选文本,可给所有Entry绑定focus-in-event信号,获得焦点时直接取消选中:

  • 信号回调函数:
def on_entry_focus_in(entry, event):
    # 取消所有选中,将光标定位到文本末尾
    entry.set_position(-1)
    return False
  • 创建Entry时绑定信号:
textEntry = Gtk.Entry()
textEntry.connect("focus-in-event", on_entry_focus_in)

两种方案均能解决切换页面时文本被自动全选、误按空格清空内容的问题,可根据实际业务场景选择。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:57:02