Search code examples
pythontkintertk-toolkit

Is it possible to center a tkinter.simpledialog window?


I'm including a conditional password capture in a larger script. The code looks like this:

if thing:  # found token, don't need password
    do stuff
else:  # no token, get password in popup
    try:
        import tkinter as tk
        import tkinter.simpledialog
        tk.Tk().withdraw()
        passwd = tkinter.simpledialog.askstring("Password", "Enter password:", show="*")
        return passwd

functionally it's fine, but most of my users are on monitors at 3840x1600 resolution, so when the dialog pops up at the top left it's easy to miss.

Is there a brief way to override the simpledialog class to tell it to appear at a certain X/Y on the monitor, or is my only option to build a full mainloop()?


Solution

  • so when the dialog pops up at the top left it's easy to miss.

    If you specify the optional argument parent, the dialogbox will appear in the middle of your window and gets the focus internally. Make sure your window is mapped via .update_idletasks() to get corresponding coordinates. You may consider also to make your window transparent instead of withdraw.

    import tkinter as tk
    import tkinter.simpledialog
    
    def ask_pw():
        pw = tkinter.simpledialog.askstring("Password",
                                            "Enter password:",
                                            show="*",
                                            parent=root)
    root = tk.Tk()
    root.geometry('250x250+500+500')
    root.update_idletasks()
    ask_pw()
    #root.withdraw()
    root.mainloop()