Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

python - Tkinter - Can't bind arrow key events

I am trying to bind the left and right arrow keys to an event in Tkinter, but when I run the program it appears the events are not triggering. Here is the code:

from Tkinter import *

main = Tk()

def leftKey(event):
    print "Left key pressed"

def rightKey(event):
    print "Right key pressed"

frame = Frame(main, width=100, height=100)
frame.bind('<Left>', leftKey)
frame.bind('<Right>', rightKey)
frame.pack()
frame.mainloop()

Why is this not working?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try binding to your main variable:

from Tkinter import *

main = Tk()

def leftKey(event):
    print "Left key pressed"

def rightKey(event):
    print "Right key pressed"

frame = Frame(main, width=100, height=100)
main.bind('<Left>', leftKey)
main.bind('<Right>', rightKey)
frame.pack()
main.mainloop()

I should explain that this works because Tk is made aware of the bindings because the main window has keyboard focus. As @BryanOakley's answer explained you could also just set the keyboard focus to the other frame:

from Tkinter import *

main = Tk()

def leftKey(event):
    print "Left key pressed"

def rightKey(event):
    print "Right key pressed"

frame = Frame(main, width=100, height=100)
frame.bind('<Left>', leftKey)
frame.bind('<Right>', rightKey)
frame.focus_set()
frame.pack()
main.mainloop()

See more about events and bindings at effbot.

Also, you could also re-write this so your application is a sub-class of Tkinter.Frame like so:

import Tkinter


class Application(Tkinter.Frame):
    def __init__(self, master):
        Tkinter.Frame.__init__(self, master)
        self.master.minsize(width=100, height=100)
        self.master.config()

        self.master.bind('<Left>', self.left_key)
        self.master.bind('<Right>', self.right_key)

        self.main_frame = Tkinter.Frame()
        self.main_frame.pack(fill='both', expand=True)
        self.pack()

    @staticmethod
    def left_key(event):
        print event + " key pressed"

    @staticmethod
    def right_key(event):
        print event + " key pressed"

root = Tkinter.Tk()
app = Application(root)
app.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...