Tkinter uses js canvas to achieve gradient color

Tkinter uses js canvas to achieve gradient color

Before, I was not very interested in GUI, but recently, due to some special reasons, I had to use tkinter and needed to implement a gradient color. However, when I looked through the documentation, I found that there was no built-in function to implement this function. I had to implement it myself, so I searched for the principle of gradient color and implemented it.

1. Use RGB to represent color

Tkinter does not provide a function that uses rgb as a parameter, so you need to convert the hexadecimal value to the grb value. Of course, the method is also very simple, which is to perform hexadecimal operations.

Code:

def use_rgb(rgb):
    """
    Convert rgb to hexadecimal Args:
        rgb: rgb colorReturns: hexadecimal """
    rgb = str(rgb)
    RGB = rgb.replace('(', '').replace(")", '').split(',') # Split the RGB format color = '#'
    for i in RGB:
        num = int(i)
        # Convert R, G, and B to hexadecimal and capitalize them. The hex() function is used to convert a decimal integer to hexadecimal and express it in string form. color += str(hex(num))[-2:].replace('x', '0')
    return color

Because the rgb passed in is in tuple form, it is converted to a string, and then converted to a hexadecimal string. Remember to add # in front of it.

2. Tkinter canvas component

The canvas component is used in the tkinter library to draw things. It can draw line segments, rectangles, polygons, arcs, etc.

To use the canvas component, you need to first create a window object as the parent object of the canvas

import tkinter as tk
# Initialize the tkinter component first and create a window object window = tk.Tk()
# Set the window title, length and width window.title("title")
window.geometry("800x600")

Nothing will happen after running, because the window needs to be displayed

window.mainloop()

Then there is a small frame with no luminous light.

The creation of canvas is also the instantiation of the creation class. It can be parameterless and adjusted later, or it can be instantiated at the same time as creation.

# Using canvas
canvas = window.Canvas()

You can also:

# window is the parent object of canvas, width and height are the width and height of canvas at a glance canvas = tk.Canvas(window, width=800, height=600)
# This method can set the layout mode, of course, it is also the method to display the canvas canvas.pack()

Of course, there is nothing after running at this time. We need to draw something on the canvas

Then we draw a rectangle through canvas

canvas.create_rectangle(100, 100, 300, 300, fill="red")
# This line of code can also be written like this canvas.create_rectangle((100, 100, 300, 300), fill="red")

This draws a red rectangle.

3. Set up the gradient

The gradient here is not directly applied on the rectangle, but requires the use of line segments, each of which displays a color, to form a gradient effect.

The method to draw a line segment is:

canvas.create_line()

The parameter format is similar to the line segment above, except that only two coordinates are needed to draw a line segment.

3.1 The principle of gradient

The simple principle is to set a color from dark to light, then to another light color, and then to dark again.

It sounds simple, but it is still a bit difficult to implement.

Our idea is:

Loop line segment

Calculate the color of each line segment

When we draw a line segment, we only need to calculate these three parameters:

Length of rectangle x-coordinate of starting point of line segment y-coordinate of starting point of line segment

The starting point here is not the initial point, but the point above the line segment.

We also need to know the RGB values ​​of the two colors we need to gradient

For gradient, we only need to know the value of a certain line segment for the beginning, and then combine it with rgb, which is the color of a certain line segment.

3.2 Example 1

Change this red rectangle into a red-blue gradient from left to right

Red grb value (255, 0, 0)

Blue RGB value (0, 0, 255)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Smly
# @datetime: 2021/12/4 19:44
#@Version: 1.0
import tkinter as tk
RED = (255, 0, 0)
BLUE = (0, 0, 255)

def use_rgb(rgb):
    """
    Convert rgb to hexadecimal Args:
        rgb: rgb colorReturns: hexadecimal """
    rgb = str(rgb)
    RGB = rgb.replace('(', '').replace(")", '').split(',') # Split the RGB format color = '#'
    for i in RGB:
        num = int(i)
        # Convert R, G, and B to hexadecimal and capitalize them. The hex() function is used to convert a decimal integer to hexadecimal and express it in string form. color += str(hex(num))[-2:].replace('x', '0')
    return color

# Initialize the tkinter component first and create a window object window = tk.Tk()
# Set the window title, length and width window.title("title")
window.geometry("800x600")
# Using canvas
canvas = tk.Canvas(window, width=800, height=600)
canvas.pack()
a1, a2, a3, b1, b2, b3 = RED[0], RED[1], RED[2], BLUE[0], BLUE[1], BLUE[2]
# Difference in rgb
r, g, b = (b1 - a1), (b2 - a2), (b3 - a3)
print(r, g, b)
h = 200
for i in range(200):
    x1 = 100 + i
    y1 = 100
    t = (x1 - 100) / (300 - 100)
    rgb = (int(a1 + r * t), int(a2 + g * t), int(a3 + b * t))
    print(rgb)
    canvas.create_line((x1, y1), (x1, y1 + h), fill=use_rgb(rgb))
window.mainloop()

Effect:

insert image description here

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • JavaScript canvas draws a rectangle with gradient colors
  • WeChat applet rainbow effect example based on canvas gradient
  • JavaScript+html5 canvas drawing gradient area complete example
  • Method of realizing multiple color gradient effects of canvas using js+HTML5

<<:  Detailed description of component-based front-end development process

>>:  How to deploy kafka in docker

Recommend

6 Uncommon HTML Tags

First: <abbr> or <acronym> These two s...

Introduction to /etc/my.cnf parameters in MySQL 5.7

Below are some common parameters of /etc/my.cnf o...

How to implement Svelte's Defer Transition in Vue

I recently watched Rich Harris's <Rethinki...

How to generate PDF and download it in Vue front-end

Table of contents 1. Installation and introductio...

CentOS 6 uses Docker to deploy Zookeeper operation example

This article describes how to use docker to deplo...

A brief discussion on group by in MySQL

Table of contents 1. Introduction 2. Prepare the ...

Bundling non-JavaScript static resources details

Table of contents 1. Custom import in packaging t...

Specific use of stacking context in CSS

Preface Under the influence of some CSS interacti...

Difference between var and let in JavaScript

Table of contents 1. Scopes are expressed in diff...

Detailed explanation of JS ES6 coding standards

Table of contents 1. Block scope 1.1. let replace...

Mysql 8.0.18 hash join test (recommended)

Hash Join Hash Join does not require any indexes ...

Analysis of 2 Token Reasons and Sample Code in Web Project Development

Table of contents question: There are 2 tokens in...

An article teaches you how to use Vue's watch listener

Table of contents Listener watch Format Set up th...

How to use JavaScript to implement sorting algorithms

Table of contents Bubble Sort Selection Sort Inse...

JavaScript to achieve fireworks effects (object-oriented)

This article shares the specific code for JavaScr...