Search code examples
pythontkintereasygui

Bring Python gui window to front?


I'm trying to use one of Python's gui modules to retrieve a user's Twitter username and password:

Here is my first attempt (using easygui):

import easygui
username = easygui.enterbox("Enter your Twitter username")
password = easygui.passwordbox("Enter your Twitter password")

Here is my second attempt (using tkinter):

import tkinter as tk
from tkinter import simpledialog

application_window = tk.Tk()
application_window.attributes("-topmost", True)
username = simpledialog.askstring("Input", "What is your Twitter username?")
password = simpledialog.askstring("Input", "What is your Twitter password?", show="*")
application_window.destroy()

Currently, the neither gui appears automatically. Rather, a Python icon appears on my Windows taskbar and I have to click the icon to make the gui appear. Is there any programmatic way to make the gui automatically pop up? Or perhaps there's another module I can use to achieve this?


Solution

  • The simpledialog module makes a new Toplevel window, which is the one you want to bring forward, not the root window.

    simpledialog works best when you already have a tkinter GUI running. I think you would be a lot better off with easygui, since it actually uses a tkinter Tk instance:

    import easygui
    
    fieldNames = ["Username", "Password"]
    values = easygui.multpasswordbox("Enter Twitter information", "Input", fieldNames)
    if values:
        username, password = values
    else:
        # user pushed "Cancel", the esc key, or Xed out the window
        username, password = None, None
    print(username, password)
    

    If that does not work, easygui has the hook to use the topmost trick:

    import easygui
    
    fieldNames = ["Username", "Password"]
    mb = easygui.multpasswordbox("Enter Twitter information", "Input", fieldNames, run=False)
    mb.ui.boxRoot.attributes("-topmost", True)
    mb.run()
    if mb.values:
        username, password = mb.values
    else:
        # user pushed "Cancel", the esc key, or Xed out the window
        username, password = None, None
    print(username, password)
    

    or just make your own dialog.