- Как закрыть окно tkinter?
- Как закрыть окно Tkinterа с помощью кнопки
- root.destroy() Метод класса для закрытия окна индикатора
- destroy() Неклассический метод закрытия окна индикатора
- Ассоциированная функция root.destroy к атрибуту command кнопки непосредственно
- root.quit для закрытия окна Tkinter
- Сопутствующая статья — Tkinter Button
- Close a window in PyQt5 in Python
- How to close a window in PyQt5
- Calling the .close() method whenever needed
- Binding to a PushButton to trigger the .close() method
- Creating a QAction and adding it to the window to trigger the .close() method
- How to close a window in Tkinter
- Destroy Function
- Quit Function
Как закрыть окно tkinter?
Выше линии только Обход root.mainloop() т.е. root.mainloop() по- прежнему будет работать в фоновом режиме, если quit() выполняется команда.
В то время как команда destroy() исчезает из root.mainloop() то есть root.mainloop() останавливается. Так как вы просто хотите выйти из программы, вы должны использовать root.destroy() как это остановит mainloop() . Но если вы хотите запустить какой-то бесконечный цикл и не хотите разрушать свое окно Tk и хотите выполнить некоторый код после root.mainloop() тогда вы должны использовать root.quit() . Пример:
from Tkinter import * def quit(): global root root.quit() root = Tk() while True: Button(root, text="Quit", command=quit).pack() root.mainloop() #do something
Если используется root.quit (), как можно позже снова найти окно в другом скрипте, который нужно уничтожить (чтобы не продолжать использовать системные ресурсы)?
Ваше первое утверждение неверно. вызов quit уничтожит все виджеты; если виджеты будут уничтожены, mainloop .
После некоторых исследований я считаю, что это также относится ко всему исполняемому коду. Поэтому, если у вас есть mainloop () TKinter в сценарии командной строки, используйте root.quit (), а не root.destroy (), иначе ваш сценарий командной строки не будет продолжать выполнять код после mainloop (). Я проверил это, и оно работает для меня (я знаю, что TKinter не предназначен для использования в таком дизайне, тем не менее, он работает)
Как закрыть окно Tkinterа с помощью кнопки
- root.destroy() Метод класса для закрытия окна индикатора
- destroy() Неклассический метод закрытия окна индикатора
- Ассоциированная функция root.destroy к атрибуту command кнопки непосредственно
- root.quit для закрытия окна Tkinter
Мы можем использовать функцию или команду, прикрепленную к кнопке в графическом интерфейсе Tkinter, чтобы закрыть окно Tkinter при нажатии на него пользователем.
root.destroy() Метод класса для закрытия окна индикатора
try: import Tkinter as tk except: import tkinter as tk class Test(): def __init__(self): self.root = tk.Tk() self.root.geometry('100x50') button = tk.Button(self.root, text = 'Click and Quit', command=self.quit) button.pack() self.root.mainloop() def quit(self): self.root.destroy() app = Test()
destroy() разрушает или закрывает окно.
destroy() Неклассический метод закрытия окна индикатора
try: import Tkinter as tk except: import tkinter as tk root = tk.Tk() root.geometry("100x50") def close_window(): root.destroy() button = tk.Button(text = "Click and Quit", command = close_window) button.pack() root.mainloop()
Ассоциированная функция root.destroy к атрибуту command кнопки непосредственно
Мы могли бы напрямую привязать функцию root.destroy к атрибуту кнопки command без определения дополнительной функции close_window .
try: import Tkinter as tk except: import tkinter as tk root = tk.Tk() root.geometry("100x50") button = tk.Button(text = "Click and Quit", command = root.destroy) button.pack() root.mainloop()
root.quit для закрытия окна Tkinter
root.quit выходит не только из окна Tkinter Window, а точнее из всего интерпретатора Tcl.
Он может быть использован, если ваше Tkinter-приложение не запущено с Python бездействующим. Не рекомендуется использовать root.quit , если ваше Tkinter-приложение вызвано из idle, потому что quit убьет не только ваше Tkinter-приложение, но и из idle, потому что idle также является Tkinter-приложением.
try: import Tkinter as tk except: import tkinter as tk root = tk.Tk() root.geometry("100x50") button = tk.Button(text = "Click and Quit", command = root.quit) button.pack() root.mainloop()
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
Сопутствующая статья — Tkinter Button
Close a window in PyQt5 in Python
Hey folks, This tutorial will help you to close a window in PyQt5 in Python. This can be achieved by using a simple method of the QWidget class. We will use that method and learn how to achieve our goal in a few ways. So for this, we are going to use some libraries of Python namely: PyQt5 and sys.
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys
How to close a window in PyQt5
To close a window in PyQt5 we use the .close() method on that window. We can simply achieve this by calling the .close() method whenever we want to close the window or by some following ways:
- Calling the .close() method whenever needed.
- Binding to a PushButton to trigger the .close() method.
- Creating a QAction and adding it to the window to trigger the .close() method.
Calling the .close() method whenever needed
Create your PyQt5 application and just call the .close() method whenever that window needs closing. For example:
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Close Window") self.l1=QLabel("Let's Close this Window") self.l1.setAlignment(Qt.AlignCenter) self.setCentralWidget(self.l1) self.close() #Closes the window at this point app=QApplication(sys.argv) window=MainWindow() window.show() app.exec_()
The above program creates a simple PyQt5 application with a QLabel as its central widget and then finally, closes it. So the window will be created, the widget will be added but it won’t be displayed as it was closed as soon as it was created.
NOTE: The above-mentioned program is just a demonstration on how to use .close() method when needed to close a window. It’s not a full-flexed application. So nothing will be displayed as mentioned earlier.
Binding to a PushButton to trigger the .close() method
In this way of closing the window, we create a QPushButton() and then bind a function(to close the window) to it which is triggered when that button is clicked. For example:
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Close Window") self.b1=QPushButton("Let's Close this Window") self.b1.clicked.connect(lambda:self.close()) #function binded to the button self.b1 self.setCentralWidget(self.b1) app=QApplication(sys.argv) window=MainWindow() window.show() app.exec_()
The above program creates a simple PyQt5 application with a QPushButton() as its central widget and then binds a function to trigger on click. The function is a simple lambda function that calls the self.close() method.It’s bound to QPushButton() using the .clicked.connect() method.So when the button is clicked the window closes.
Creating a QAction and adding it to the window to trigger the .close() method
In this way of closing the window, we create a QAction() and then add that action to the window we want to close using the .addAction() method. For example:
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Close Window") self.l1=QLabel("Let's Close this Window") self.l1.setAlignment(Qt.AlignCenter) self.setCentralWidget(self.l1) self.exit=QAction("Exit Application",shortcut=QKeySequence("Ctrl+q"),triggered=lambda:self.exit_app) self.addAction(self.exit) def exit_app(self): print("Shortcut pressed") #verification of shortcut press self.close() app=QApplication(sys.argv) window=MainWindow() window.show() app.exec_()
The above program creates a simple PyQt5 application with a QLabel as its central widget. Then a QAction() is created with some parameters like the name of the action, shortcut and triggered. Where shortcut is the key or key sequence that is needed to be pressed to trigger that action. Also, the triggered parameter is where the function to call on that action being triggered is specified. Then that action is added to the window which needs to be closed using the .addAction() So when the shortcut specified(i.e. Ctrl+q ) is pressed, as expected, the window closes.
How to close a window in Tkinter
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() .
from tkinter import * def close(): root.destroy() root = Tk() root.geometry('200x100') button = Button(root, text = 'Close the window', command = close) button.pack(pady = 10) root.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 .
from tkinter import * root = Tk() root.geometry('200x100') button = Button(root, text = 'Close the window', command = root.destroy) button.pack(pady = 10) root.mainloop()
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.
from tkinter import * def destroy(): button.destroy() root = Tk() root.geometry('200x100') button = Button(root, text = 'Close the window', command = destroy) button.pack(pady = 10) root.mainloop()
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.
from tkinter import * root = Tk() root.geometry('200x100') button = Button(root, text = 'Close the window', command = root.quit) button.pack(pady = 10) root.mainloop()
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.
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.