简体   繁体   中英

Python Gtk 3.0: How to grab focus inside Notebook

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!

As it turns out , you can only grab focus to visible widgets.

Calling grab_focus after show_all makes the example work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM