简体   繁体   中英

How to bind keyboard event to Python tkMessageBox?

I'm developing a small GUI application which is required to work with a wireless presenter pointer, which has only two keys: left arrow and right arrow. I can bind keyboard event "Left" and "Right" to the root (the main window) and call a function, so most part of my application works fine.

But when I need to pop up a message box with tkMessageBox to show some information, the only way to click "OK" button with keyboard is to press "space", which is not there on my presenter pointer. It means when such a message box is popped up, the presenter have to go to the computer to either click the "OK" button with mouse, or "space" key with keyboard.

Is there any way allowing me to temporarily bind "left arrow" or "right arrow" to the "OK" button when such a message box is popped up and then restore the binding of both the keys back to there original on_click function?

As the tkMessageBox is not an object but a tcl call, you cannot overload bindings that easy. Just subclass Tkinter.Frame to get an object where keys can be bound.

Subclassing could nevertheless follow the look and feel of a MessageBox.

eg

#!/usr/bin/python
import Tkinter

class MyBox(Tkinter.Toplevel):
    def __init__(self, *args, **kwargs):
        Tkinter.Toplevel.__init__(self, *args, **kwargs)
        self.__text = Tkinter.StringVar()
        self.__text.set("Initialized Text")
        Tkinter.Label(self, textvariable = self.__text).grid(row=0, column=0, columnspan=3, sticky=Tkinter.NW+Tkinter.SE)
        Tkinter.Button(self, text="OK", command=self.release_func).grid(row=1, column=1, sticky=Tkinter.NW+Tkinter.SE)
        self.bind_all("&ltKeyRelease>", self.release_func)
        self.grid()
        self.focus_set()
    def set_text(self, text="NoText"):
        self.__text.set(text)
        self.focus_set()
    def release_func(self, event=None):
        # event=None necessary as we also use button binding.
        self.destroy()

root = Tkinter.Tk()
messagebox = MyBox()
messagebox.set_text("Show this message")
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM