Search code examples
gtkgtk3pygtk

Editable label in Python GTK+ 3?


I'm new to GTK programming. I want to have a Label widget whose text can be edited, kind of like this: https://docs.gtk.org/gtk4/class.EditableLabel.html.

The problem is I have no idea how to implement this. I understand that Gtk.Button has a set_label() function, though I don't know how to use it to make an editable label.


Solution

  • You can do that with Gtk.Entry which you can set_editable based on "something". Example with check button would look something like this:

    import gi
    gi.require_version("Gtk", "3.0")
    from gi.repository import Gtk
    
    
    def on_editable_toggled(button, entry):
        value = button.get_active()
        entry.set_editable(value)
        entry.set_sensitive(value)
        
    
    win = Gtk.Window()
    win.connect("destroy", Gtk.main_quit)
    
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
    win.add(vbox)
    
    entry = Gtk.Entry()
    entry.set_text("Hello World")
    
    vbox.pack_start(entry, True, True, 0)
    
    check_editable = Gtk.CheckButton(label="Editable")
    check_editable.connect("toggled", on_editable_toggled, entry)
    check_editable.set_active(True)
    
    vbox.pack_start(check_editable, True, True, 0)
    
    win.show_all()
    Gtk.main()
    

    It doesn't really look like a label, but you can use the Gtk CSS styling to change the background and border colors to make it look like one when it is set to non-editable.