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="Color Selection Dialog") self.button = Gtk.Button(label="Pick a color") self.button.connect("clicked", self.on_button_clicked) self.add(self.button) def on_button_clicked(self, widget): dialog = Gtk.ColorSelectionDialog(title="Pick a color") response = dialog.run() if response == Gtk.ResponseType.OK: color = dialog.get_color_selection().get_current_color() print("Selected color is:", color) dialog.destroy() win = MyWindow() win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main()
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk class MyWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Color Selection Dialog") color = Gdk.Color(red=0xffff, green=0x3333, blue=0x3333) self.color_button = Gtk.Button(label="Set initial color") self.color_button.connect("clicked", self.on_color_button_clicked) self.add(self.color_button) def on_color_button_clicked(self, widget): dialog = Gtk.ColorSelectionDialog(title="Pick a color") color = Gdk.Color(red=0x9999, green=0x9999, blue=0xffff) dialog.get_color_selection().set_current_color(color) response = dialog.run() if response == Gtk.ResponseType.OK: color = dialog.get_color_selection().get_current_color() print("Selected color is:", color) dialog.destroy() win = MyWindow() win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main()In both examples, we import the Gtk module from the gi.repository package and create a subclass of the Gtk.Window widget. Inside this class, we create a button to trigger the ColorSelectionDialog, which is created and displayed when the button is clicked. In the first example, we simply get the selected color from the dialog, print it to the console, and destroy the dialog. In the second example, we set an initial color for the ColorSelectionDialog and allow the user to choose a different one. Overall, Gtk ColorSelectionDialog is a useful widget for allowing the user to choose colors in a graphical way, and can be easily integrated into any Python Gtk application using the gi.repository library.