Python Forum
How to get RGB colors in tkinter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get RGB colors in tkinter
#1
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
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#2
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:
   
Reply
#3
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()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#4
equivalents:
150, 150, 210 = #9696d2
80, 0, 20 = #500064
25, 100, 200 = #1964c8
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I get Colors of current GTK theme? ondoho 2 6,343 May-26-2017, 03:32 PM
Last Post: ondoho

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020