Title: Use tkinter sliders to select a color's red, green, and blue components in Python
This is a pretty simple example that lets you use sliders to set a color's red, green, and blue color components. The program uses the following code to build its user interface.
# Initialize tkinter.
self.window = tk.Tk()
self.window.title('color_sliders')
self.window.protocol('WM_DELETE_WINDOW', self.kill_callback)
self.window.geometry('300x300')
# Red.
self.red_scale = tk.Scale(self.window, from_=0, to=255,
orient=tk.HORIZONTAL, command=self.show_color,
background='pink')
self.red_scale.set(255)
self.red_scale.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
# Green.
self.green_scale = tk.Scale(self.window, from_=0, to=255,
orient=tk.HORIZONTAL, command=self.show_color,
background='light green')
self.green_scale.set(255)
self.green_scale.pack(side=tk.TOP, fill=tk.X, padx=5, pady=(0,5))
# Blue.
self.blue_scale = tk.Scale(self.window, from_=0, to=255,
orient=tk.HORIZONTAL, command=self.show_color,
background='light blue')
self.blue_scale.set(255)
self.blue_scale.pack(side=tk.TOP, fill=tk.X, padx=5, pady=(0,5))
# Hex display.
self.hex_color_var = tk.StringVar(self.window, value='#ffffff')
hex_color_entry = tk.Entry(self.window, state='readonly',
textvariable=self.hex_color_var, justify='center')
hex_color_entry.pack(side=tk.BOTTOM, fill=tk.X, pady=(0,5))
# Canvas.
self.canvas = tk.Canvas(self.window, bg='white', borderwidth=2,
relief=tk.SUNKEN)
self.canvas.pack(side=tk.TOP, fill=tk.BOTH,
expand=True, padx=5, pady=(0,5))
# Tkinter main loop.
self.window.mainloop()
The progam first initializes tkinter. I then creates three Slider widgets for the color's red, green, and blue color components. Each of the sliders calls the show_color method when its value changes.
Next, the code makes an Entry widget where it can display the current color's hexadecimal representtation. The widget is read-only so you can't type in it but you can copy and paste its value to use in other programs.
The code finishes by creating a Canvas widget and starting the tkinter event loop.
The following code shows the show_color method.
def show_color(self, _):
r = self.red_scale.get()
g = self.green_scale.get()
b = self.blue_scale.get()
color = f'#{r:02x}{g:02x}{b:02x}'
self.canvas.configure(bg=color)
self.hex_color_var.set(color)
This code gets the sliders' values and uses an f-string to convert them into a hexadecimal string representing the selected color. The method sets the Canvas widget's background to that color and displays it in the Edit widget.
Download the example to see additional details.
|