Tkinter 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.

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.

Читайте также:  Html код красивой ссылки

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.

Читайте также:  Программирование python minecraft pdf

Он может быть использован, если ваше 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

Источник

Создание окна по центру и кнопка выхода в Tkinter

Создание окна в Tkinter

В этой части обучения Tkinter мы познакомим Вас с инструментом Tkinter и создадим первые программы. Целью этого руководства является ознакомление с базой инструментария Tkinter. Я использовал несколько иконок из набора Tango от Gnome project.

Tkinter библиотека для создания графических интерфейсов

Tkinter – это графическая библиотека на основе Tk, которая входит в стандартную библиотеку Python. Tk является библиотекой базовых элементов графического интерфейса для языка Tcl. Tkinter реализован как оболочка Python для Tcl интерпретатора, встроенного в интерпретатор Python. Существует и несколько других популярных графических инструментов для Python. Наиболее популярными являются wxPython, PyQt5 и PyGTK.

Язык программирования Python

Python – это высокоуровневый, динамичный, объектно-ориентированный язык программирования. Он ориентирован на повышение производительности программиста и читаемости кода. Разработчиком кода является Гвидо ван Россум. Впервые язык увидел свет в 1991 году. При создании Python, автор вдохновлялся такими языками программирования как ABC, Haskell, Java, Lisp, Icon и Perl. Python является высокоуровневым, кроссплатформенным, но в то же время минималистичным языком. Одним из его основных преимуществ является отсутствие скобок и точек с запятой. Вместо этого Python использует отступы. Сегодня существует две основные ветви языка: Python 2.7 и Python 3.x.

Стоит отметить, что Python 3 нарушает обратную совместимость с предыдущими версиями языка. Его разработали для того, чтобы исправить ряд недостатков конструкции уже существующего языка, упростить и очистить его от ненужных деталей. Последней версией Python 2.x является 2.7.17, а Python 3.x – 3.8.5. Данный учебник написан на Python 2.x, равно как и большая часть кода. Мы обновили учебник под Python 3.8.

Читайте также:  Php убираем дубликаты строк

Для перехода программного обеспечения и самих разработчиков на Python 3.x потребуется какое-то время. Уже перешли все на Python 3. Сегодня Python поддерживается большим количеством добровольцев со всего мира. Напомню, что язык имеет открытый исходный код.

Python – это идеальный язык для тех людей, которые хотят научиться программировать.

Язык программирования Python поддерживает несколько стилей программирования. Он не принуждает разработчика придерживаться определенной парадигмы. Python поддерживает объектно-ориентированное и процедурное программирование. Существует и ограниченная поддержка функционального программирования.

Создание обычного окна в Tkinter

В нашем первом примере мы покажем стандартное окно на экране.

Источник

Python Tkinter Exit Program

In this section, we will learn how to exit the program in Python Tkinter.

Python Tkinter Exit Program

To quit a program we need to destroy the window. There is a built-in method destroy () to close the window in Python Tkinter.

Here ws is the main window & is the variable for Tk() class method.

Here is the the small demonstration of Python Tkinter Exit Program.

In this code, we have created a simple button on the window. When the user will click on the button it will close the window.

from tkinter import * from tkinter import messagebox from time import * def close(): ws.destroy() ws = Tk() ws.title("PythonGuides") ws.geometry("400x300") ws['bg']='#5d8a82' Button( ws, text="EXIT PROGRAM", font=("Times", 14), command=close ).pack(pady=100) ws.mainloop()

In this output, Button with the text “Exit Program” is displayed. When user will click on this button the window will close.

python tkinter exit program

You may like the following Python tutorials:

So in this tutorial, we have learned how to exit the program in Python Tkinter or how to quit the program in python Tkinter.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

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