- Hide console window of python .py on windows
- Hide console window of python .py on windows
- How to hide console window in python when python app
- How To Hide Tkinter python Gui
- How to hide console when displaying an image with Tkinter
- Hide console for Tkinter app on OSX
- Как скрыть окно консоли в python?
- 6 ответов
- Update
- В Unix-системах (включая Linux, macOS и BSD)
- В системах Windows
Hide console window of python .py on windows
Python Launcher is a very simple-minded app that starts Python via a Terminal.app command. Not a very good solution, since you have to use the subprocess module just to open an image. but anyways. alternatively you could use and use (assuming windows here) With os.system the console will show but only very briefly.
Hide console window of python .py on windows
You need to use the pythonw.exe program as it won’t open a terminal when ran.
How to hide console window in python?, This will hide your console. Implement these lines in your code first to start hiding your console at first. import win32gui, win32con the_program_to_hide = win32gui.GetForegroundWindow () win32gui.ShowWindow (the_program_to_hide , win32con.SW_HIDE) Update May 2020 : Usage examplewin32gui.ShowWindow(the_program_to_hide , win32con.SW_SHOW)Feedback
How to hide console window in python when python app
https://tinyurl.com/yr9nhjmy in this video i will show you how to remove console wind ow in python when any python application opens,in this video i will show
How To Hide Tkinter python Gui
To hide the default root window you can use
and to make it visible again you can use
from tkinter import Tk root = Tk() root.withdraw()
If you want to «hide» the window (NOT destroy it) and bring it back, then the way to do that is set the alpha channel.
To hide the window, set the alpha channel to 0:
to restore the window set alpha to 1.0:
[EDIT — had the incorrect type/range for the original answer. Range is 0 to 1.0 and is a float]Python 3.x — Hide console window with Tkinter and, I am using cx_freeze to freeze a tkinter app. When I run the exe I get a wonderfully USELESS console window along with my tkinter GUI. I would like to remove/hide this useless black window. I’ve seen threads that suggest the following: root = tkinter.Tk() root.withdraw() The above code does the opposite …
How to hide console when displaying an image with Tkinter
I dont know how to do this through pure tk but if subprocess is an option then you can do the following. Not a very good solution, since you have to use the subprocess module just to open an image. but anyways.
import tkinter as tk import subprocess as s root = tk.Tk() def open_image(): s.call(["tobi.jpg"], shell=True) button = Button(root) button.config(text="Show the Image", command=open_image, activebackground="yellow", bg="lightgreen") button.pack() root.mainloop()
alternatively you could use os and use os.system(«start my_file_name.jpg») (assuming windows here)
With os.system the console will show but only very briefly.
Really doing the same thing, opening with PIL is just slower than others, so you see the console for a longer period.
U can use the following code:`
import win32console import win32gui win=win32console.GetConsoleWindow() # For closing command window win32gui.ShowWindow(win,0)
This will close the cmd window at start itself, and will not show again. The cmd window may show for a very little time at first, as a blink, then it will not show. u can save in .py extention.
from Tkinter import * from PIL import Image import win32console import win32gui win=win32console.GetConsoleWindow() # For closing command window win32gui.ShowWindow(win,0) def open_image(): im = Image.open("tobi.jpg") im.show() root = Tk() root.geometry("800x600+400+300") buton = Button(root) buton.config(text = "Show the image", command = open_image, activebackground = "yellow", bg = "lightgreen") buton.pack() mainloop()
How to hide Windows console with python Tkinter?, I tried renaming my .py file to .pyw. But compiling with py2exe does not make a difference. I tried using root.withdraw() but all it does is freeze the application, prevent the initial canvas from popping up, and fail to remove the command prompt window anyways.
Hide console for Tkinter app on OSX
By double-clicking a .py file on OS X, you are likely launching a Python gui instance via the Python Launcher.app supplied with OS X Pythons. You can verify that by selecting the .py file in the Finder and doing a Get Info on it. Python Launcher is a very simple-minded app that starts Python via a Terminal.app command. To directly launch your own Python GUI app, the preferred approach is to create a simple app using py2app. There’s a brief tutorial here.
There are other ways, of course, but most likely any of them would be adding more levels of indirection. To make a normal launchable, «double-clickable» application, you need some sort of app structure. That’s what py2app lets you create directly.
A very simple-minded alternative is to take advantage of the AppleScript Editor’s ability to create a launcher app. In the AppleScript editor:
- /Applications/Utilities/AppleScript Editor.app in OS X 10.6
- /Applications/AppleScript/Script Editor.app in 10.5
make a new script similar to this:
do shell script "/path/to/python /path/to/script.py &> /dev/null &"
and then Save As.. with File Format -> Application . Then you’ll have a double-clickable app that will launch another app. You can create something similar with Apple’s Automater.app . But, under the covers, they are doing something similar to what py2app does for you, just with more layers on top.
Adding to the answer by Ned Deily, im my case when I tried to launch the Python application using an AppleScript application, it did not work initially. I discovered that it has something to to with some kind of encoding error (I am using UTF-8 and in the past I had felt need to configure it to UTF-8).
So, after further investigation, I discovered that I can accomplish this by creating an AppleScript application with the following code (adjusting the paths of python3 and of the Python application as needed):
do shell script «export LC_ALL=en_US.UTF-8; export LANG=en_US.UTF-8; /usr/local/bin/python3 ‘/Users/USER/FOLDER/SCRIPT.py’ &> /dev/null &»
It launches the Python application without any Terminal windows. The AppleScript application can then be personalised with a custom icon as usual, and can be placed in the Dock. When clicked, it will launch the Python intepreter, that still shows up in Dock, but with no visible windows.
I think this may be useful to other users.
‘console hide’ doesn’t hide the Terminal in OS X. It hides Tk’s built-in console, which is really a relic from the MacOS Classic days (and which is still commonly used on Windows).
How to hide the console window while starting Tkinter, In Python 3’s standard library, Tkinter was renamed tkinter. The raw_input was accidentally left behind from when I was initially testing to see how raw_input would work in Python 2. It didn’t work when I allocated a new console, so I investigated why and determined that fixing it would be more work than it was …
Как скрыть окно консоли в python?
Я пишу IRC-бот в Python. Я хочу создать автономные двоичные файлы для Linux и Windows. И в основном я хочу, чтобы при запуске бота окно консоли должно скрываться, и пользователь не должен был видеть это окно. Что я могу сделать для этого?
6 ответов
Просто сохраните его с расширением .pyw . Это предотвратит открытие окна консоли.
В системах Windows нет понятия «исполняемый режим». Установщик Python автоматически связывает файлы.py с файлом python.exe, чтобы двойной щелчок на файле Python запускал его как скрипт. Расширение также может быть.pyw, в этом случае окно консоли, которое обычно появляется, подавляется.
В linux просто запустите его, без проблем. В Windows вы хотите использовать исполняемый файл pythonw.
Update
Хорошо, если я понимаю вопрос в комментариях, вы спрашиваете, как сделать окно команд, в котором вы запустили бот из командной строки?
Я думаю, что правильно. В любом случае, теперь вы можете закрыть терминал.
Это не основная проблема . Основная проблема заключается в том, чтобы скрыть окно консоли, когда программа работает. Как это сделать?
Измените расширение файла на .pyw, чтобы связать его с pythonw.exe oreilly.com/catalog/pythonwin32/chapter/ch20.html.
«nohup mypythonprog &» поможет мне в Linux . но Python не будет установлен на Windows-машине. Так что «start pythonw mypythonprog» не поможет мне, я думаю.
Хорошо, если Puython не установлен, у вас есть другая проблема. Вы хотите, чтобы py2exe создавал отдельный исполняемый файл. logix4u.net/Python/Tutorials/… и py2exe.org/index.cgi/FrontPage
unix ≠ Linux, unix ≠ UNIX, вышеупомянутое решение работает также для macOS и BSD (они unix), без форматирования кода.
В Unix-системах (включая Linux, macOS и BSD)
Используйте nohup mypythonprog & , и вы можете закрыть окно терминала, не нарушая процесс. Вы также можете запустить exit , если вы работаете в облаке, и не хотите оставлять зависающий процесс оболочки.
В системах Windows
Сохраните программу с расширением .pyw , и теперь она будет открыта с помощью pythonw.exe . Нет окна оболочки.
Например, если у вас есть foo.py , вам нужно переименовать его в foo.pyw .
Если все, что вы хотите сделать, это запустить Python Script на компьютере с Windows, на котором установлен Python Interpreter, преобразование расширения вашего сохраненного Script из ‘.py’ в ‘.pyw’ должно сделать трюк,
Но если вы используете py2exe для преобразования вашего Script в автономное приложение, которое будет запускаться на любой машине Windows, вам нужно внести следующие изменения в ваш файл setup.py.
Следующий пример представляет собой простой python-GUI, созданный с использованием Tkinter:
from distutils.core import setup import py2exe setup (console = ['tkinter_example.pyw'], options = < 'py2exe' : >)
Измените «консоль» в приведенном выше коде на «windows»..
from distutils.core import setup import py2exe setup (windows = ['tkinter_example.pyw'], options = < 'py2exe' : >)
Это откроет только созданный графический интерфейс Tkinter и отсутствие окна консоли.
Хотя я чувствую, что этот ответ немного не по теме для вопроса, я все равно оставил его, поскольку он отвечает на следующий вопрос (ссылка ниже), который был помечен как дубликат этого вопроса.
Я на самом деле использую pyinstaller, но он имеет опцию для того же (-w) и исправил проблему для меня.
Дополнительная информация. для ситуаций, в которых потребуется решение win32gui, опубликованное Мохсеном Хаддади ранее в этой теме:
Дополнительная информация о пакете pywin32 находится на: Как использовать модуль win32gui с Python? ,
Кроме того, чтобы применить дискрецию при закрытии окна, чтобы случайно не закрыть какое-либо окно на переднем плане, разрешение можно расширить по следующим строкам:
try : import win32gui, win32con; frgrnd_wndw = win32gui.GetForegroundWindow(); wndw_title = win32gui.GetWindowText(frgrnd_wndw); if wndw_title.endswith("python.exe"): win32gui.ShowWindow(frgrnd_wndw, win32con.SW_HIDE); #endif except : pass