Simple slider with keyboard input
Hi, I just want to share a simple slider that I made.
It is controlled by a keyboard, and make use of the keyboard function get_key_release() so it dose not work with the psycho backend.
The output is normalized to be between 0 and 1.
import time
c = Canvas()
keyboard = Keyboard(keylist=['left','right'])
# Configuration: Slider limits and setp size
min_pos, max_pos = -402, 398
step_right, step_left = 1, -1
# Timeout settings
timeout_duration = 3
last_input_time = time.time()
# Current position for marker
cur_pos = min_pos
## Normalize value to [0,1]
def normalize(value, min_val=min_pos, max_val=max_pos):
return (value - min_val) / (max_val - min_val)
# Draw marker
def draw_marker(pos, step):
      if step > 0:
            new_pos = min(max_pos, pos+step)
      else:
            new_pos = max(min_pos, pos+step)
      c['marker'] = Rect(new_pos,-20,5,40, color='red', fill=True)
      c.show()
      return new_pos
# Draw line
c['slide_line'] = Rect(-400,-2,800,4, color='white', fill=True)
draw_marker(cur_pos, 0)
c.show()
while True:
      key, _ = keyboard.get_key(timeout=100)
      if time.time() - last_input_time > timeout_duration:
            break
      if key:
            while True:
                  key_release, timestamp = keyboard.get_key_release(timeout=10)
                  last_input_time = time.time()
                  
                  if key_release:
                        break
                  step = step_left if key == 'left' else step_right if key == 'right' else 0
                  if step:
                        del c['marker']
                        cur_pos = draw_marker(cur_pos, step)
print(normalize(cur_pos))
                 
				 
							 
							
Comments
Hi @SpacePenguins,
Thanks for this! It's very neat and works nicely! It's a great starting point for anyone interested in a modified version of this slider.
I used some AI to introduce acceleration of the cursor when an arrow key stays down, and to collect the position when the space bar is pressed (instead of using the timeout method).
Best,
Fab.
Thanks of the feedback @Fab!
I should have mention that the value is selected when the marker is not moved for 3 seconds. I choose this method because we will use it to collect a rating from participants inside a MR and we only have two buttons for the participant to interact with.
Thank you for the acceleration it works great and feels much smoother!