Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use rgb in tkinter?

Can I use rbg instead of hex in tkinter? If so, how can I do it? I am planning to use this feature to make sort of a gradient from one color to another and I plan to make a for loop to change it from 1 to 255 in a few seconds.

from tkinter import *

root = Tk()
root.configure(background="can i use rgb instead of hex here?")
root.mainloop()
like image 790
Morton Madison Wally Avatar asked Jul 30 '18 09:07

Morton Madison Wally


2 Answers

No, tkinter does not support RGB, but you can write a small helper function to remedy this:

Maybe something like this, where the argument rgb must be a valid rgb code represented as a tuple of integers.

import tkinter as tk


def _from_rgb(rgb):
    """translates an rgb tuple of int to a tkinter friendly color code
    """
    return "#%02x%02x%02x" % rgb   

root = tk.Tk()
root.configure(bg=_from_rgb((0, 10, 255))) 
root.mainloop()

If you find it more readable, you can also use fstrings to achieve the exact same result:

def _from_rgb(rgb):
    """translates an rgb tuple of int to a tkinter friendly color code
    """
    r, g, b = rgb
    return f'#{r:02x}{g:02x}{b:02x}'

Note that the colorsys module from the Python standard library can help translate from HSV, HLS, and YIQ color systems

like image 95
Reblochon Masque Avatar answered Sep 23 '22 15:09

Reblochon Masque


def rgbtohex(r,g,b):
    return f'#{r:02x}{g:02x}{b:02x}'

print(rgbtohex(r=255, g=255, b=255))

Hope this helps some of you

like image 26
philippbecker Avatar answered Sep 25 '22 15:09

philippbecker