2

So tkinker can only use one key at a time. I am unable to say move to the left and up at the same time with this example. How would i go about doing it if I wanted to?

import tkinter
root = tkinter.Tk()
root.title('test')
c= tkinter.Canvas(root, height=300, width=400)
c.pack()
body = c.create_oval(100, 150, 300, 250, fill='green')

def key(event):
    OnKeyDown(event.char)
    print(event.char)

def MoveLeft(evenr)
    c.move(body, -10, 0)

def MoveRight(event):
    c.move(body, 10, 0)

def MoveUp(event):
    c.move(body, 0, 10)

def MoveDown(event):
    c.move(body, 0, -10)

root.bind('<KeyPress-Left>', MoveLeft)
root.bind('<KeyPress-Right>', MoveRight)
root.bind('<KeyPress-Up>', MoveUp)
root.bind('<KeyPress-Down>', MoveDown)

Personally I would also prefer to not have to "bind" my keys to functions as well as I also would like to use the keys to preform other actions (ie: make it move faster if I hold shift and up at the same time) Can tinker recognize when you pre-assign two keys or hold two keys at the same time?

martineau
  • 119,623
  • 25
  • 170
  • 301
skyzzle
  • 167
  • 1
  • 4
  • 16
  • That sounds like quite a game like requirement. I'm not certain tkinter was created to meet such requirements. Having said that perhaps one way round that is to use a state machine design. So pressing each key down sets a flag and releasing the key unsets the flag. You would then have a function running in a loop, which periodically checks those flags and if they are set moves your shape. If it detects only up it moves up, if it detects up and left it moves up and left and so on. – Paul Rooney Sep 21 '16 at 02:21
  • 1
    Tk has both KeyPress and KeyRelease events, as well as root.after timer events. You don't need a continual loop, but after an arrow key down event, you could wait to move until either another arrow key is pressed or, say, 1/20 second (50 milleseconds) elapses. Pick the time based on experiments. You then have to decide whether keeping the key(s) down generates more moves or not. – Terry Jan Reedy Sep 21 '16 at 03:47

1 Answers1

3

Like this :

from Tkinter import *

root = Tk()
var = StringVar()
a_label = Label(root,textvariable = var ).pack()

history = []
def keyup(e):
    print e.keycode
    if  e.keycode in history :
        history.pop(history.index(e.keycode))

        var.set(str(history))

def keydown(e):
    if not e.keycode in history :
        history.append(e.keycode)
        var.set(str(history))

frame = Frame(root, width=200, height=200)
frame.bind("<KeyPress>", keydown)
frame.bind("<KeyRelease>", keyup)
frame.pack()
frame.focus_set()
root.mainloop()

Don't forget toggle keys because got a little mix status.

dsgdfg
  • 1,492
  • 11
  • 18