Search code examples
pythonpython-3.xgtk3

Python GTK3: button with image and label and get the Label value after click event


I'm trying to get the label value that is inside a Grid and that grid is inside a button after a click event.

This is my part of code:

for one_text in text_list:
    label_for_button = Gtk.Label(one_text)
    label_for_button.set_line_wrap(True)
    image_for_button = Gtk.Image.new_from_file("img.png")
    grid_in_button = Gtk.Grid()
    grid_in_button.add(image_button)
    grid_in_button.attach_next_to(label_for_button, image_for_button, Gtk.PositionType.BOTTOM, 1, 2)
    grid_in_button.show_all()
    button.add(grid_in_button)

    button.connect("clicked", self.on_button_clicked)

def on_button_clicked(self, widget):
    # here i wanna get the value of the label_for_button

Help.. Any idea? Thanks


Solution

  • hope this code helps:

    import gi
    gi.require_version('Gtk','3.0')
    from gi.repository import Gtk,GdkPixbuf
    
    def btn_clicked(widget):
        print(widget.get_label())
    
    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename="img.png", width=24, height=24, preserve_aspect_ratio=True)
    img = Gtk.Image.new_from_pixbuf(pixbuf)
    btn = Gtk.Button(label='some text',image=img,)
    btn.connect('clicked',btn_clicked)
    win = Gtk.Window()
    win.connect("destroy", Gtk.main_quit)
    win.add(btn)
    win.show_all()
    Gtk.main()