Python Gtk 3.0: How to grab focus inside Notebook

Hello everyone,

I’m trying to set the focus to an Entry input field. If I put it inside a Box, I can set the focus via the grab_focus method. But if the Entry is inside a Notebook, it is not focused.

Example code:

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk


class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Simple Notebook Example")
        self.set_border_width(3)

        self.notebook = Gtk.Notebook()
        self.add(self.notebook)

        self.page1 = Gtk.Box()
        self.page1.set_border_width(10)
        self.page1.add(Gtk.Label(label="Default Page!"))
        self.notebook.append_page(self.page1, Gtk.Label(label="Plain Title"))

        self.note = Gtk.Entry()
        self.note.set_activates_default(True)
        self.note.set_text("")
        self.page1.add(self.note)

        self.page2 = Gtk.Box()
        self.page2.set_border_width(10)
        self.page2.add(Gtk.Label(label="A page with an image for a Title."))
        self.notebook.append_page(
            self.page2, Gtk.Image.new_from_icon_name("help-about", Gtk.IconSize.MENU)
        )

        self.note.grab_focus()  # does not work


win = MyWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

How can I focus self.note inside the notebook?

Thanks for any help!

PS: If you have an answer, feel free to post it on Stackoverflow, if you are interested in the bounty.

You can only grab focus to visible widgets.

1 Like

Hey, thanks for the answer!

If I call the grab_focus after win.show_all(), it does work! :slight_smile:

win = MyWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
win.note.grab_focus()
Gtk.main()

Thanks!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.