Nirvik Baruah
Nirvik Baruah

Reputation: 1793

Keyup handler in Tkinter?

The title says it all. Is there a something in Tkinter I can call which will let me monitor specific key releases and let me link it to a function? I want to use it to let me end a timer that I am using to move my item. Here is the code:

from Tkinter import *

master = Tk()
master.wm_title("Ball movement")

width = 1000
height = 600
circle = [width / 2, height / 2, width / 2 + 50, height / 2 + 50]

canvas = Canvas(master, width = width, height = height, bg = "White")
canvas.pack()
canvas.create_oval(circle, tag = "ball", fill = "Red")

while True:
    canvas.update()
    def move_left(key):
        #This is where my timer will go for movement
        canvas.move("ball", -10, 0)
        canvas.update()
    def move_right(key):
        #This is where my other timer will go
        canvas.move("ball", 10, 0)
        canvas.update()
    frame = Frame(master, width=100, height=100)
    frame.bind("<Right>", move_right)
    frame.bind("<Left>", move_left)
    frame.focus_set()
    frame.pack()

mainloop()

Upvotes: 4

Views: 4095

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385830

You can define events prefixed with KeyRelease, such as <KeyRelease-a>. For example:

canvas.bind("<KeyRelease-a>", do_something)

Note: you need to remove your while loop. You should never create an infinite loop inside a GUI program, and you definitely don't want to be creating a frame every iteration -- you'll end up with thousands of frames in only a second or two!

You already have an infinite loop running, mainloop. If you want to do animation, use after to run a function every few milliseconds. For example, the following will cause a ball to move 10 pixels every 10th of a second. Of course, you'll want to handle the case where it moves off screen or bounces or whatever. The point is, you write a function that draws one frame of animation, and then have that function be called periodically.

def animate():
    canvas.move("ball", 10, 0)
    canvas.after(100, animate)

Upvotes: 5

Related Questions