Programer Beginner
Programer Beginner

Reputation: 1429

How to make Canvas widget color darker compared to the original color?

I have this canvas widget with a green rectangle:

canvas = tk.Canvas(root)
canvas.create_rectangle(0,0,50,100, fill='green')

I want to darken it. So:

canvas.itemconfig(1, fill=?????)

The issue is, what should I put in the ????? aka the 'darker' color of the original color.

Sure, I can just find a hex for a darker shade of green or something like that, but the point is: How can I find the darkened the widget based on the original color?

I don't necessarily need to find the darker version of the color if there is something like: canvas.itemconfig(1, darkness=-100).

Upvotes: 0

Views: 648

Answers (1)

Mike - SMT
Mike - SMT

Reputation: 15236

Here is a simple example of how to use a function to lower the color based on a RGB tuple that is converted to hex. We start out with a lightish green and with each button press it gets darker. This is a simple example but I am sure you can adapt it for your needs.

import tkinter as tk

root = tk.Tk()

cv = (110, 160, 50)
canvas = tk.Canvas(root)
rect = canvas.create_rectangle(0,0,50,100, fill="#%02x%02x%02x" % cv)
canvas.pack()

def darker():
    global cv
    greater = True
    cv = (cv[0]- 10, cv[1] - 10, cv[2] - 10)
    for item in cv:
        if item < 0:
            greater = False

    if greater == True:
        canvas.itemconfig(rect, fill = "#%02x%02x%02x" % cv)

tk.Button(root, text="Darker", command=darker).pack()

root.mainloop()

Or you can do this using the current preferred concatenation with format():

import tkinter as tk

root = tk.Tk()

cv = (110, 160, 50)
canvas = tk.Canvas(root)
rect = canvas.create_rectangle(0,0,50,100, fill = "#{}".format("".join("{:02X}".format(a) for a in cv)))
canvas.pack()

def darker():
    global cv
    greater = True
    cv = (cv[0]- 10, cv[1] - 10, cv[2] - 10)
    for item in cv:
        if item < 0:
            greater = False

    if greater == True:
        canvas.itemconfig(rect, fill = "#{}".format("".join("{:02X}".format(a) for a in cv)))

tk.Button(root, text="Darker", command=darker).pack()

root.mainloop()

Upvotes: 1

Related Questions