Python Forum

Full Version: How to get RGB colors in tkinter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Posted some examples in another thread about colors in tkinter.
Just wanted to post a couple ways to get RGB colors in tkinter.

For python2.7
#! /usr/bin/env python2.7
from struct import pack

def rgb_color(rgb):
    return('#' + pack('BBB', *rgb).encode('hex'))

print(rgb_color((255, 69, 123)))
Output:
#ff457b
For python3.+
from base64 import b16encode

def rgb_color(rgb):
    return(b'#' + b16encode(bytes(rgb)))

print(rgb_color((255, 69, 123)))
Output:
b'#FF457B'
This works with all versions I tested
def rgb_color(rgb):
    return '#%02x%02x%02x' % rgb

print(rgb_color((200, 100, 25)))
Output:
#c86419
use standard color codes with format #ff80bf or standard names red, blue, etc.
these can be displayed on any widget that allows attributes fg or bg
some examples:
import tkinter as tk

class Colors:
    def __init__(self, parent):
        self.initialize_window(parent)

    def initialize_window(self, parent):
        # give it some size
        parent.geometry("600x400+50+50")
        # and a title
        parent.title('Show your Colors')
        # add a frame with background color
        frame = tk.Frame(parent, bg='#ff80bf')
        frame.pack(fill=tk.BOTH, expand=1)
        # add a button (to frame) with different color
        btn = tk.Button(frame, text='Frame Button', bg='#80bfff')
        btn.pack()
        # add a button to parent with yet a different color
        btn1 = tk.Button(parent, text='Parent Button', bg='#ffdf80')
        btn1.pack()


def main():
    root = tk.Tk()
    Colors(root)
    root.mainloop()


if __name__ == '__main__':
    main()
results:
[attachment=849]
I guess I should have posted an example. I should have named the title to How to add rgb colors to tkinter.
#! /usr/bin/env python3.8
'''Docstring'''
import tkinter as tk
from base64 import b16encode

def rgb_color(rgb):
    return(b'#' + b16encode(bytes(rgb)))


root = tk.Tk()
root.geometry('600x400+50+50')
root.configure(bg=rgb_color((150, 150, 210)))
btn = tk.Button(root, text='This is some text', fg=rgb_color((80, 0, 200)), bg=rgb_color((25, 100, 200)))
btn.pack()
root.mainloop()
equivalents:
150, 150, 210 = #9696d2
80, 0, 20 = #500064
25, 100, 200 = #1964c8