0

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.

Navot Naor
  • 59
  • 5

2 Answers2

1

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.

Henry Yik
  • 22,275
  • 4
  • 18
  • 40
  • Thank you @HenryYik that workes great, but 2 quick follow up questions, how to i get the arrow up action to also terminate the gui? and how to i not only print but also log the answer? – Navot Naor Oct 20 '19 at 13:06
  • Instead of lambda you can always define a function to do what you want. You can include root.quit() and your mechanism to store the result. – Henry Yik Oct 20 '19 at 13:08
0

Thank you for @Henry Yik This is how i ended up doing is

import tkinter

def quit():
    global tkTop
    tkTop.destroy()

def savepick(event):
    global colornumber
    colornumber = tkScale.get()
    print (colornumber)
    return (colornumber)

def doscale(tkScale):
    savepick(tkScale)
    quit()


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)
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>", doscale)

tkinter.mainloop()
Navot Naor
  • 59
  • 5