Tkinter Scale Set Window Background Color
One feature of the Scale control is that it can automatically trigger events when it is moved. We can set the callback method to be executed when moving by adding the command parameter when using Scale( ).
def callback():
.
.
.
sliderObj = Scale(..., command = callback)
From the above, we can see that the callback() method will be called and executed when there is a scale bar movement.
Tkinter Scale Set Window Background Color Example#1
Three scale bars are designed to represent R, G, and B. When moving these three scale bars, Python Shell will display the color values of these three scale bars, and you can see that the window background color will also change in real time.
from tkinter import *
def bgUpdade(source): # Note:The parameter source is required here
''' Change window background color '''
red = rSlider.get() # Read red value
green = gSlider.get() # Read green value
blue = bSlider.get() # Read blue value
print("R=%d, G=%d, B=%d" % (red, green, blue)) # Print color values
myColor = "#%02x%02x%02x" % (red,green,blue) # Converting colors to hexadecimal strings
print(myColor) # Print this string representing the color
root.config(bg=myColor) # Set window background color
root = Tk()
root.title("apidemos.com")
root.geometry("360x240")
rSlider = Scale(root,from_=0,to=255,label="Red Portion",command=bgUpdade)
gSlider = Scale(root,from_=0,to=255,label="Green Portion",command=bgUpdade)
bSlider = Scale(root,from_=0,to=255,label="Blue Portion",command=bgUpdade)
gSlider.set(125) # Set the initial value of the green component to 125
rSlider.grid(row=0, column=0) # row=0,col=0
gSlider.grid(row=0, column=1) # row=0,col=1
bSlider.grid(row=0, column=2) # row=0,col=2
root.mainloop()
Output:
The following is what is displayed in the Python Shell window, which records changes in RGB color values.
The above design is to place the scale bar in the upper left corner of the window, which is not very convenient if you want to adjust the position. The best way to design is to design a container first, and then place the three scale bars inside this container, so that if you want to move the position in the future, you can directly move the container position.