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()
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With