Спрятать окно tkinter
Проблема следующая. Пользуюсь модулем messagebox, который, помимо окна диалога, создает пустое окно root. Чтобы спрятать это окно, на форумах советуют использовать root.withdraw(). Однако мой скрипт создает много разнообразных окон tkinter, и после того, как я что-нибудь нажал в диалоге messagebox, tkinter не может создать новое окно (терминал просто висит) — видимо, ждет, когда я закрою пустое окно root (оно, напомню, спрятано, т.е. мне остается только Ctrl+C). root_destroy() в конце таких процедур как ниже не помогает. Если же withdraw убрать, tkinter начинает плодить сущности: 1, 2 — некрасиво. Как можно решить этот вопрос?
Никак. В Tk обязательно есть root-окно. Цикл wm (основной цикл для Windows Manager’a Tk) обязательно должен содержать рутовое окно (иначе просто не к чему привязать цикл). Ну, и для Tk использование диалоговых окон вне цикла — просто не возможно. Дело в том, что исходя из архитектуры Tk, элемент message box — это просто дочернее окно (следовательно, оно должно быть привязано к root’овому), у которого заранее заданы определенные параметры.
Я такую проблему обходил просто — сделал класс, который описывал нужный мне диалог и создавал/убивал окно по мере надобности (каждый раз это было просто заново создаваемое root’овое окно). Для Tk это более правильный подход, нежели скрывать корневое окно, а потом плодить мессадж-боксы.

Второй путь: забить на Tk и юзать Gtk 🙂

А смысл? Для маленьких скриптов — tk самое оно. Тем более, что Tkinter — гвидоугодный.
How to close a window in Tkinter
report this ad
report this ad
report this ad
This article explains how to close the tkinter window
There are many different ways to close a Tkinter window. The easiest and simplest way is to click the «X» button on the window. However, this method is rather crude and not very suitable for all situations that you may come across.
Here we’ll be exploring methods which allow you greater control over how your program exits and closes the Tkinter window. We’ll be covering the use of two functions, quit() and destroy() used for this purpose.
Destroy Function
The destroy function will cause Tkinter to exit the mainloop() and simultaneously, destroy all the widgets within the mainloop() .
The window produced by the above code. Clicking the button will destroy the window, causing it to disappear along with any other widgets in it.

You can also optimize the above code by removing the function, and directly having the button call the destroy function on root .
When you use command = root.destroy you pass the method to the Button without the parentheses because you want Button to store the method for future calling, not to call it immediately when the button is created.
Bonus fact, the destroy function works on more than just the Tkinter window. You can use it on individual widgets as well. Try running the following code and see for yourself.
You can learn more about the destroy() function in it’s own dedicated tutorial.
Quit Function
The quit() function is rather confusing, because of which it’s usually a better (and safer) idea to be using the destroy() function instead. We’ll explain how to use the quit() function to close a tkinter window here anyway.
The quit() function will exit the mainloop, but unlike the destroy() function it does not destroy any existing widgets including the window. Running the below code will simply stop the TCL interpreter that Tkinter uses, but the window (and widgets) will remain.
The quit function can cause problems if you call your application from an IDLE. The IDLE itself is a Tkinter application, so if you call the quit function in your app and the TCL interpreter ends up getting terminated, the whole IDLE will also be terminated.
For these reasons, it’s best to use the destroy function.
Related Articles:
This marks the end of the Tkinter close window article. Any suggestions or contributions for Coderslegacy are more than welcome. Questions regarding the article can be asked in the comments section below.

report this ad
How do I get rid of Python Tkinter root window?
Do you know a smart way to hide or in any other way get rid of the root window that appears, opened by Tk() ? I would like just to use a normal dialog.
Should I skip the dialog and put all my components in the root window? Is it possible or desirable? Or is there a smarter solution?
8 Answers 8
Probably the vast majority of of tk-based applications place all the components in the default root window. This is the most convenient way to do it since it already exists. Choosing to hide the default window and create your own is a perfectly fine thing to do, though it requires just a tiny bit of extra work.
To answer your specific question about how to hide it, use the withdraw method of the root window:
If you want to make the window visible again, call the deiconify (or wm_deiconify) method.
Once you are done with the dialog, you can destroy the root window along with all other tkinter widgets with the destroy method:
Python-сообщество
Использую messagebox, который, помимо диалога, создает пустое окно root
. Для скрытия этого окна на форумах предлагается использовать root.withdraw(), но после этого я не всегда могу снова использовать окна Tkinter, потому что он ждет, пока я закрою скрытое окно root. Если же не скрывать пустые окна, они плодятся
. Могу ли я как-нибудь по-другому избавиться от этого окна или полностью закрыть все окна Tkinter перед его повторным использованием?
#2 Апрель 1, 2013 20:38:55
Скрыть окно Tkinter
Возможно вы не хотите закрывать главное окно и потом заново его создавать. Возможно вы просто хотите скрывать и вновь отображать одно и то же главное окно, а что на нем отображается можно менять как вам угодно.
Если же вы действительно хотите то о чем просите, то вам просто необходимо использовать метод destroy экземпляра Tk (root в вашем случае). Но мне кажется что вы ставите задачу не совсем правильно.
#3 Апрель 2, 2013 00:11:09
Скрыть окно Tkinter
Griffon Вы абсолютно правы. Вопрос поставлен неккоректно.
Вопрос должен быть следующим:
“Каким образом удалить корневое окно, вывод которого скрыт методом .withdraw()?”
В результате имеет то, что окна размножаются при каждом вызове и естественно, обращение к ним блокируется.
Ну так удаляйте их. Кто за Вас это будет делать? Пример кода: