Skip to content Skip to sidebar Skip to footer

Tkinter - Define "custom Colors" For Colorchooser

I am currently using a colorchooser from tkinter in a project to allow the user to choose a custom colour. Minimally, this can be created (in Python 3.x) through from tkinter impor

Solution 1:

What you see is the common Color dialog box, which is native Windows dialog. It's not possible to specify custom colors within tkinter, because they're handled at a lower level.

The naive implementation (using ctypes) could be something like this:

import ctypes
import ctypes.wintypes as wtypes


classCHOOSECOLOR(ctypes.Structure):
    """" a class to represent CWPRETSTRUCT structure
    https://msdn.microsoft.com/en-us/library/windows/desktop/ms646830(v=vs.85).aspx """

    _fields_ = [('lStructSize', wtypes.DWORD),
                ('hwndOwner', wtypes.HWND),
                ('hInstance', wtypes.HWND),
                ('rgbResult', wtypes.COLORREF),
                ('lpCustColors', ctypes.POINTER(wtypes.COLORREF)),
                ('Flags', wtypes.DWORD),
                ('lCustData', wtypes.LPARAM),
                ('lpfnHook', wtypes.LPARAM),
                ('lpTemplateName', ctypes.c_char_p)]


classColorChooser:
    """ a class to represent Color dialog box
    https://msdn.microsoft.com/en-gb/library/windows/desktop/ms646912(v=vs.85).aspx """
    CC_SOLIDCOLOR = 0x80
    CC_FULLOPEN = 0x02
    custom_color_array = ctypes.c_uint32 * 16
    color_chooser = ctypes.windll.Comdlg32.ChooseColorW

    defto_custom_color_array(self, custom_colors):
        custom_int_colors = self.custom_color_array()

        for i inrange(16):
            custom_int_colors[i] = rgb_to_int(*custom_colors[i])

        return custom_int_colors

    defaskcolor(self, custom_colors):
        struct = CHOOSECOLOR()

        ctypes.memset(ctypes.byref(struct), 0, ctypes.sizeof(struct))
        struct.lStructSize = ctypes.sizeof(struct)
        struct.Flags = self.CC_SOLIDCOLOR | self.CC_FULLOPEN
        struct.lpCustColors = self.to_custom_color_array(custom_colors)

        if self.color_chooser(ctypes.byref(struct)):
            result = int_to_rgb(struct.rgbResult)
        else:
            result = Nonereturn result


defrgb_to_int(red, green, blue):
    return red + (green << 8) + (blue << 16)


defint_to_rgb(int_color):
    red = int_color & 255
    green = (int_color >> 8) & 255
    blue = (int_color >> 16) & 255return red, green, blue

colors = [(250, 0, 0), (0, 250, 0), (0, 0, 250), (255, 255, 255)] * 4

chooser = ColorChooser()
result_color = chooser.askcolor(colors)
print(result_color)

Remember, that there's a room for expansion, for example, preserving the custom color array between calls and supporting of hex colors/arbitrary array length.

Solution 2:

No, there is no way to pre-fill the custom colors from tkinter.

Post a Comment for "Tkinter - Define "custom Colors" For Colorchooser"