Search code examples
pythonuser-interfaceeventsreturngtk

python Gtk3 return value when button clicked


I have a main python program A.py that calls a GUI Gtk python program, B.py, to display a window. I want this window being color buttons and when I click on one, the main A.py code recover a value, the RGB color value.

A.py

import B
c = B.gui_color()
print(c)

B.py

class W(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="colors")
        self.box = Gtk.Box(spacing=0, homogeneous=True)
        self.add(self.box)

        colors = j.load("colors.json")

        for c in colors:
            b = Gtk.Button()
            b.connect("clicked", self.return_color, c["value"])
            # x257 to get the GTK color
            b.modify_bg(Gtk.StateType.NORMAL, Gdk.Color(c["value"][0] * 257, c["value"][1] * 257, c["value"][2] * 257))
            self.box.pack_start(b, True, True, 0)

    def return_color(self, widget, *color):
        self.close()
        return color[0]

def gui_color():
    w = W()
    w.connect("destroy", Gtk.main_quit)
    w.show_all()
    Gtk.main()

Everything is ok with the program, I get my window with multiple color buttons, however I can not figure out how to recover the color I clicked on. The return action in the return_color doesn't return to the A.py program. How can I perform that? Should I use stdout with print? I precise that after having clicking, I would like to do others actions that won't need a GUI at all.


Solution

  • Before return color[0] in the return_color do self.selected_color = color[0], after Gtk.main() do return w.selected_color