Peng He
Peng He

Reputation: 2213

How do I quit a keyboard event in Tkinter?

I want to make a keyboard quick operation command.When I press 'b',print 'b';and When I press 's',print 's' .Here is my code:

# -*- coding: utf-8 -*-
from Tkinter import *
import tkFont

root = Tk()

def pri(event):
    print event.char

def rb():
    root.bind('<KeyPress-b>',pri)
    root.bind('<KeyPress-s>',pri)

v = IntVar()
def callbackcheck():
    if v.get():
        rb()
Cb = Checkbutton(root,variable = v,text = 'Hello',onvalue = 1,offvalue  = 0,command = callbackcheck)
Cb.pack()

root.mainloop()

When I set the Checkbutton 'on',keyboard event is activated.But when I set the Checkbutton 'off',keyboard event can't quit and when I press 'b',still print 'b'.Actually,keyboard event always run once it was activated.And I don't know how to quit keyboard event.Do you have any ideas?

Next is a similar question: When I use entry in Tkinter,I just want input numbers,not letters,and I find a way to use validateCommand.But I can't quit the entry widget when I click other area in current window or input letters.I want to exit the entry widget when I click other widget or input letters,how can I achieve this goal?

Upvotes: 1

Views: 1843

Answers (2)

Nander Speerstra
Nander Speerstra

Reputation: 1526

EDITED

As Zetys points out, you have to unbind the key-command combination. Based on your code:

# -*- coding: utf-8 -*-
from Tkinter import *
import tkFont

root = Tk()

def pri(event):
    print (event.char)

def rb():
    if v.get():
        root.bind('<KeyPress-b>',pri)
        root.bind('<KeyPress-s>',pri)
    else:
        root.unbind('<KeyPress-b>')
        root.unbind('<KeyPress-s>')

v = BooleanVar()

Cb = Checkbutton(root,variable = v,text = 'Hello', command = rb)
Cb.pack()

root.mainloop()

I changed few things:

  • I deleted callbackcheck (rb does the trick now)
  • I changed the IntVar to BooleanVar, so that it is either 'True' or 'False' (no need to explicitly call onvalue and offvalue).

Upvotes: 2

Kenly
Kenly

Reputation: 26698

You should remove binding with unbind() when you set the Checkbutton 'off' .

if v.get():
    rb()
else:
    root.unbind('<KeyPress-b>')
    root.unbind('<KeyPress-s>')

Upvotes: 2

Related Questions