How can I control keyboard repeat delay in a Tkinter root window?

时光怂恿深爱的人放手 提交于 2019-12-04 16:10:20

This is not something configurable in Tk -- Tk has no control over how fast the keyboard driver sends repeated key events.

What you can do instead is have a binding on the button press and button release to set and then unset a flag. Then, you can write a function that does whatever you want it to do, then check the flag and call itself again after whatever delay you want.

The function would look something like this:

def hello(x):
    global SHOULD_REPEAT
    print "hello"
    if SHOULD_REPEAT:
        root.after(10, hello) # wait 10ms then repeat

To do it right requires a little bit more logic, but that's the general idea.

Below is a complete example based on Bryan's answer in this post:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def step(*event):
    label['text'] += 1


    if label._repeat_on:
        root.after(label._repeat_freq, step)


def stop(*event):
    if label._repeat_on:
        label._repeat_on = False
        root.after(label._repeat_freq + 1, stop)
    else:
        label._repeat_on = True


if __name__ == '__main__':
    root = tk.Tk()
    label = tk.Label(root, text=0)
    label._repeat_freq = 10
    label._repeat_on = True

    root.bind('<KeyPress-s>', step)
    root.bind('<KeyRelease-s>', stop)

    label.pack()
    root.mainloop()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!