Автоматическое закрытие окна python

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.

Tkinter close window

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.

Читайте также:  Typescript throw new error

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.

Источник

Как закрыть окно Tkinterа с помощью кнопки

Как закрыть окно Tkinterа с помощью кнопки

  1. root.destroy() Метод класса для закрытия окна индикатора
  2. destroy() Неклассический метод закрытия окна индикатора
  3. Ассоциированная функция root.destroy к атрибуту command кнопки непосредственно
  4. 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() разрушает или закрывает окно.

Tkinter закрывает окно кнопкой

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

Источник

PyQt5 закрытие окна не прерывающее скрипт

Здравствуйте! Мне нужно вывести PyQt окно подождать пока юзер нажмёт на кнопку, закрыть окно и продолжить скрипт. Кто знает как это сделать?

Именно так и делать — вывести окно, закрыть окно и продолжить скрипт не убивая его через sys.exit(. ) или же отловил вызванное этой функцией исключение SystemExit .

2 ответа 2

Перепробовал все варианты, и понял, что лучше всего подходит метод close()

Ну, в общем-то да, вызвать close() при нажатии на кнопку и продолжить без принудительного завершения скрипта sys.exit(. ) . Все правильно, мне добавить нечего. Думаю, пример уже не нужен?

import sys from PyQt5.QtCore import QPropertyAnimation, Qt, QRectF from PyQt5.QtGui import QFontDatabase from PyQt5.QtWidgets import (QPushButton, QApplication, QStyleOptionButton, QStylePainter, QStyle) class PushButtonFont(QPushButton): LoadingText = "\uf110" def __init__(self, *args, **kwargs): super(PushButtonFont, self).__init__(*args, **kwargs) self.resize(250, 250) self.fontSize = self.font().pointSize() * 2 self._rotateAnimationStarted = False self._rotateAnimation = QPropertyAnimation(self) self._rotateAnimation.setTargetObject(self) self._rotateAnimation.setStartValue(1) self._rotateAnimation.setEndValue(12) self._rotateAnimation.setDuration(1000) self._rotateAnimation.setLoopCount(-1) # Бесконечная петля self._rotateAnimation.valueChanged.connect(self.update) self.clicked.connect(self._onClick) def paintEvent(self, _): option = QStyleOptionButton() self.initStyleOption(option) painter = QStylePainter(self) if self._rotateAnimationStarted: option.text = "" painter.drawControl(QStyle.CE_PushButton, option) if not self._rotateAnimationStarted: return painter.save() font = self.font() font.setPointSize(self.fontSize) font.setFamily("FontAwesome") painter.setFont(font) # преобразовать координаты в середину painter.translate(self.rect().center()) # поворот на 90 градусов painter.rotate(self._rotateAnimation.currentValue() * 30) fm = self.fontMetrics() # Положительный средний текст после преобразования координат w = fm.width(self.LoadingText) h = fm.height() painter.drawText( QRectF(0 - w * 2, 0 - h, w * 2 * 2, h * 2), Qt.AlignCenter, self.LoadingText) painter.restore() def _onClick(self): if self._rotateAnimationStarted: self._rotateAnimationStarted = False self._rotateAnimation.stop() return self._rotateAnimationStarted = True self._rotateAnimation.start() def update(self, _=None): super(PushButtonFont, self).update() if __name__ == "__main__": app = QApplication(sys.argv) # Загрузка шрифтов в библиотеку шрифтов QFontDatabase.addApplicationFont( "Fonts/FontAwesome/fontawesome-webfont.ttf") w = PushButtonFont("Нажмите, чтобы загрузить " "fa_spinner") w._onClick() w.show() sys.exit(app.exec_()) 

введите сюда описание изображения

Похожие

Подписаться на ленту

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.7.25.43544

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Источник

Триггер на закрытие программы на Python [дубликат]

Мне нужно сделать так, что бы когда программа закрывалась, я смог это отследить и на основе этого что то сделать, в моем случае это занести это в мой логфайл.

from tkinter import * и остальные библеотеки. def exit1(): print('exit') logging.basicConfig(filename='LogFile.log', level=logging.INFO) class Window: там идут функции некоторые if __name__ == '__main__': try: exit1() except RuntimeError as error: print(error) finally: logging.info(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " Closing the program") window = Window(600, 500, "Название программые") window.run() 

2 ответа 2

Мне нужно сделать так, что бы когда программа закрывалась

Код после инструкции finnaly, это последнее что делает Python Interpreter, перед закрытием программы.

def main(): print('Hello World') if __name__ == '__main__': try: main() raise RuntimeError() except Exception as error: print(error) finally: print('Bye bye. ') # Здесь можно записать данные в лог # Даже если возникнет исключение 

С чем связанно, то, что у меня сначала пишется в логах, что прога закрылась, а только потом, те действия которые были сделаны в проге? Как это пофиксить можно, sleep() не работает

Дополню, что можно обрабатывать разные сигналы которые поступают программе с помощью модуля signal . В этом примере регистрируется обработчик для сигнала SIGINT — сигнал для остановки процесса пользователем с терминала Ctrl + C . В библиотеке можно найти полный перечень сигналов. При нажатии Ctrl + C — будет выполнен код signal_handler .

import signal import time def signal_handler(signal, frame): print('handler start') time.sleep(1) # тут можно выполнить любую операцию print('sleepeng') signal.signal(signal.SIGINT, signal_handler) # регистрация обработчика while 1: print(1) time.sleep(2) 

Стоит учесть, что Обработчики сигналов выполняются в основном потоке Python, независимо от того из какого потока был получен. Это означает, что сигналы не могут использоваться в качестве средства связи между потоками.

Источник

Оцените статью