Search code examples
pythontkinterwidgetbindsimpledialog

Python tkinter simpledialog. How to bind a key to the OK button in simpledialog


def prompt_new_name(self):
    new_name = simpledialog.askstring("Name Change", "New name")
    if new_name is not None:
        self.request_name_change(new_name)

I want to bind enter key on the keypad to the OK button in the simpledialog askstrinig prompt. (realized later normal enter key is already bound, but I need both enter keys to be bound) I know how to bind enter key to a widget using bind function. However, to do that I need a reference to the widget.

For this case, I don't have the reference to the widget since I am calling askstring fuction on simpledialog without making the widget. I am wondering how I can achieve what I want.


Solution

  • SimpleDialog is "simple". Create own dialog (using TopLevel widget) if you need something different.


    Or see SimpleDialog source code to recreate askstring

    https://fossies.org/dox/Python-3.5.0/simpledialog_8py_source.html

    import tkinter as tk
    import tkinter.simpledialog 
    
    class My_QueryString(tkinter.simpledialog._QueryString):
    
          def body(self, master):
              self.bind('<KP_Enter>', self.ok) # KeyPad Enter
              super().body(master)
    
    def myaskstring(title, prompt, **kw):
        d = My_QueryString(title, prompt, **kw)
        return d.result
    
    #---------------------------------------------------------
    
    root = tk.Tk()
    
    new_name = myaskstring("Name Change", "New name")
    if new_name:
        print(new_name)
    
    root.mainloop()