Search code examples
pythonpython-3.xconsolepysimplegui

How to toggle the console with a button in a GUI program


When I run my program (.exe file), the console automatically turns on. I don't want to get rid of it, but I want to have the ability to hide it. I know that I can completely get rid of the console while coverting .py to .exe with the auto-py-to-exe module.

Is there a way to turn the console on and off with a button, without closing the program or anything like that? I am using the PySimpleGui Library for the gui if that changes anything.

The Button:

Console toggle button


Solution

  • Try to use pywin32 library to hide/show the console, and it work only for WINDOWS.

    import win32gui, win32con
    import PySimpleGUI as sg
    
    console = win32gui.GetForegroundWindow()
    
    sg.theme("DarkBlue3")
    sg.set_options(font=("Courier New", 12))
    
    layout = [[sg.Button( "Console ON/OFF", key="-CONSOLE-")]]
    window = sg.Window('Title', layout, finalize=True)
    
    view_console = True
    while True:
    
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        elif event == "-CONSOLE-":
            view_console = not view_console
            option = win32con.SW_SHOW if view_console else win32con.SW_HIDE
            win32gui.ShowWindow(console, option)
    
    window.close()