tkintertkinter-scale

How to create a scale, control it with keyborad arrows, and log single value using tkinter


I am writing a shot pygame based game/experiment, at certain point during the game a question is meant to pop-up asking the participants to recall the number things he just saw. I am trying to crate a scale that would move left and right using arrows only (we are running in an fMRI scanner, so there is no mouse) and would log one value from the scale using a 3rd button press (say arrow pointing up).

import tkinter

def quit():
    global tkTop
    colorchange = float(var.get())
    tkTop.destroy()


tkTop = tkinter.Tk()
tkTop.geometry('300x200')

tkButtonQuit = tkinter.Button(tkTop, text="Enter", command=quit)
tkButtonQuit.pack()

tkScale = tkinter.Scale(tkTop, from_=0, to=5, orient=tkinter.HORIZONTAL, variable = var)
tkScale.pack(anchor=tkinter.CENTER)

tkinter.mainloop()

i wish to get one value to have one value for colorchange that would be logged n the parent main script. I would also like to change the allow for keyboard control, not mouse only.


Solution

  • Tkinter provides events and bindings for operations like this. You can take a look at here.

    Basically you are looking to bind the events <Left> and <Right> to either decrease or increase your Scale widget. It can be something like this:

    tkScale = tkinter.Scale(tkTop, from_=0, to=5, orient=tkinter.HORIZONTAL)
    tkScale.pack(anchor=tkinter.CENTER)
    
    tkTop.bind("<Left>", lambda e: tkScale.set(tkScale.get()-1))
    tkTop.bind("<Right>", lambda e: tkScale.set(tkScale.get()+1))
    tkTop.bind("<Up>", lambda e: print (tkScale.get()))
    

    Note that I chose to bind on your root window tkTop instead of your tkScale. If you want the key binding to work only when your Scale widget has focus, you can change to tkScale.bind(...) instead.