0

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?

Vespene Gas
  • 3,210
  • 2
  • 16
  • 27
  • Post your minimal code so you can get assistance – AD WAN Jan 18 '18 at 10:25
  • 2
    You should delevolp your own MessageBox to implement the _click() function you want to use. This might help :https://stackoverflow.com/questions/29619418/how-to-create-a-custom-messagebox-using-tkinter-in-python-with-changing-message – Gwendal Grelier Jan 18 '18 at 10:25
  • You _can_ restore your binds to original but the problem is if you can actually bind to tkMessageBox. – Nae Jan 18 '18 at 12:26
  • 1
    if you are on windows or osx, there's no way to bind any keys to the dialogs. – Bryan Oakley Jan 18 '18 at 12:53

1 Answers1

1

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.

e.g.

#!/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&gt", 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()
R4PH43L
  • 2,122
  • 3
  • 18
  • 30