Python - TKinter. Is there way to detect if Scale (slider) value was changed while specific key was pressed?

82 Views Asked by At

I have Scale widget to set int-value for color of circle to draw. In default way we just set value for the color variable:

def get_color(value):
    figures_color.set(value)

scale_color = tk.Scale(root, label='Color', variable = figures_color, from_=1200, to=24000, orient=tk.HORIZONTAL, length=500, showvalue=0, tickinterval=2000, command=get_color)

But I'm interested in other option. If scale value was changed while Shift key was pressed, we need to mark that circle should be also filled with some color. Something like this:

def get_color_fill(event):
    fill_circle = True

But I have no idea how to make it in proper way (or if it is even possible). Any suggestions?

1

There are 1 best solutions below

8
Dinux On

You can use the .bind() method in Tkinter to run a function on a key press. Example code:

def get_color_fill(event):
    fill_circle = True

def get_color(value):
    figures_color.set(value)

scale_color = tk.Scale(root, label='Color', variable = figures_color, from_=1200, to=24000, orient=tk.HORIZONTAL, length=500, showvalue=0, tickinterval=2000, command=get_color)

scale_color.bind('<Shift-KeyPress>', get_color_fill) #Using the .bind() method

Another way to check if a key was pressed is to use the keyboard module. You need to first install it using:

pip install keyboard 

Then in your code:

import keyboard

def get_color_fill(event):
    fill_circle = True

def get_color(value):
    if not keyboard.is_pressed('shift'):
        figures_color.set(value)

    elif keyboard.is_pressed('shift'):
        get_color_fill()

scale_color = tk.Scale(root, label='Color', variable = figures_color, from_=1200, to=24000, orient=tk.HORIZONTAL, length=500, showvalue=0, tickinterval=2000, command=get_color)

The second method is better, since you want to run the get_color_fill() function if the shift key is pressed while changing the value of the scale.