python-2.7gtk3gtkentry

Gtk Widget add_child fails with error


I am trying to create a custom Gtk text entry. The basic idea is to put a button inside of a text entry. Here is a shortened version of my full code:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
builder = Gtk.Builder()
button = Gtk.Button('button')
entry = Gtk.Entry()
entry.add_child(builder, button, "button")

The button does not get shown and it fails with the error:

(pygtk_foobar.py:26622): Gtk-CRITICAL **: gtk_buildable_add_child: 
assertion 'iface->add_child != NULL' failed

Any suggestions?


Solution

  • A GtkEntry widget is not a GtkContainer, and thus it cannot have child widgets added or removed to it.

    Only widgets that inherit from the GtkContainer class can have children in GTK+.

    If you want to put a button next to a text entry, you should pack both widgets into a container like GtkBox, e.g.:

    box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=2)
    entry = Gtk.Entry()
    button = Gtk.Button(label='button', hexpand=True)
    box.add(entry)
    box.add(button)
    box.show_all()
    

    This will create a box with an entry and a button.