Как закрыть окно tkinter в python
Перейти к содержимому

Как закрыть окно tkinter в python

  • автор:

Создать окно Tkinter и закрыть его после выполнения процедуры

Мне нужно вставить progress bar на выполнение определенной процедуры (желательно, без использования дополнительных тредов) или хотя бы отобразить окно «Please wait. » и закрыть его после выполнения процедуры.

root=Tk() frame=Frame(root) label=Label(frame,text='Please wait. ') label.pack() frame.pack() smart_search(['Принцесса','на','горошине']) root.mainloop()
from tkinter import ttk root = Tk() progressbar = ttk.Progressbar(orient=HORIZONTAL, length=200, mode='determinate') progressbar.pack(side="bottom") progressbar.start() smart_search(['Принцесса','на','горошине']) progressbar.stop() root.mainloop()

В обоих случаях окна появляются ПОСЛЕ выполнения процедуры. Как исправить?

Deleted
09.12.13 22:36:37 MSK

Python-сообщество

[RSS Feed]

  • Начало
  • » Python для новичков
  • » Как закрыть окно в Tkinter Python?

#1 Ноя. 26, 2017 07:19:04

Vilgelm Зарегистрирован: 2017-10-04 Сообщения: 7 Репутация: -1 Профиль Отправить e-mail

Как закрыть окно в Tkinter Python?

Нужно чтобы по нажатию кнопки “Играть” закрывалось данное окно

from tkinter import * root = Tk() root.geometry("100x100") btn = Button(root, text = 'Играть', background="#555", foreground="#ccc", padx="10", pady="5", font="16", ) btn.pack() 

attachment

Прикреплённый файлы:
2BAEG.png (9,0 KБ)

#2 Ноя. 26, 2017 16:51:30

DamMercul Зарегистрирован: 2017-11-26 Сообщения: 319 Репутация: 13 Профиль Отправить e-mail

Как закрыть окно в Tkinter Python?

Исправь на:

def exitting(): global root root.destroy() exit() btn = Button(root, text = 'Играть', command=exitting, background="#555", foreground="#ccc", padx="10", pady="5", font="16", ) 

Интересно только — зачем?
Зачем тебе надо делать кнопку ИГРАТЬ, которая заставляет человека выйти?

# Life loop while alive: if (fun > boredom) and money: pass_day(fun, boredom, money) continue else: break 

Отредактировано DamMercul (Дек. 3, 2017 10:37:49)

Close a Tkinter Window With a Button

Close a Tkinter Window With a Button

  1. root.destroy() Class Method to Close the Tkinter Window
  2. destroy() Non-Class Method to Close the Tkinter Window
  3. Associate root.destroy Function to the command Attribute of the Button Directly
  4. root.quit to Close the Tkinter Window

We can use a function or command attached to a Tkinter button in the Tkinter GUI to close the Tkinter window when the user clicks it.

root.destroy() Class Method to Close the Tkinter Window

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() method destroys or closes the window. We make a separate quit method and then bind it to the command of the button.

We could also directly set the command argument to be self.root.destroy as below.

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.root.destroy)  button.pack()  self.root.mainloop()   def quit(self):  self.root.destroy()  app = Test() 

Tkinter close a window with a button

destroy() Non-Class Method to Close the Tkinter Window

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() 

Associate root.destroy Function to the command Attribute of the Button Directly

We could directly bind root.destroy function to the button command attribute without defining the extra function close_window any more.

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 to Close the Tkinter Window

root.quit quits not only the Tkinter Window but, more precisely, the whole Tcl interpreter.

It could be used if your Tkinter app is not initiated from Python IDLE . We don’t recommend to use root.quit if your Tkinter app is called from IDLE because quit will kill not only your Tkinter app but also the IDLE because IDLE is also a Tkinter application.

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.

Related Article — Tkinter Button

  • Pass Arguments to Tkinter Button Command
  • Change Tkinter Button State
  • Bind Multiple Commands to Tkinter Button
  • Create a New Window by Clicking a Button in Tkinter
  • Change the Tkinter Button Size

Как закрыть окно tkinter при клике не на него [закрыт]

Закрыт. Этот вопрос необходимо уточнить или дополнить подробностями. Ответы на него в данный момент не принимаются.

Хотите улучшить этот вопрос? Добавьте больше подробностей и уточните проблему, отредактировав это сообщение.

Закрыт 3 года назад .
Как закрыть окно tkinter (Python) при клике не на него
Отслеживать
задан 18 июл 2020 в 3:24
Ahmed Ayman 123 Ahmed Ayman 123
141 13 13 бронзовых знаков
А кликнуть куда вы хотели бы?
18 июл 2020 в 3:55

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

Вот так это можно сделать:

from tkinter import * root = Tk() root.bind("", lambda x: root.destroy()) root.mainloop() 

Отслеживать
ответ дан 18 июл 2020 в 4:41
11.8k 2 2 золотых знака 10 10 серебряных знаков 28 28 бронзовых знаков

В таком случае окно закрывается когда на него нажимают, а мне нужно наоборот, если нажали не на окно, а в другом месте, то окно закрывается

19 июл 2020 в 12:21

  • python
  • python-3.x
  • tkinter
  • окно
    Важное на Мете
Похожие

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

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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *