簡體   English   中英

關閉 python tkinter 中的所有 windows

[英]closing all windows in python tkinter

我正在使用 python 中的 tkinter 庫。 我有一個主 window,它有幾個按鈕,當點擊這些按鈕時,會彈出一個新的 window,它還有一個名為取消的按鈕。 我想為所有 windows 設置取消按鈕。

我嘗試了以下解決方案,它只關閉當前的 window。

from tkinter import *
from tkinter import ttk
import  tkinter.messagebox

import datetime

import tkinter as tk


class AlertDialog:
    def __init__(self):
        self.invalidDiag = tk.Toplevel()
        invalidInput = tk.Label(master=self.invalidDiag,
                                text='Error: Invalid Input').grid(row=1, column=1)
        closeButton = tk.Button(master=self.invalidDiag,
                                text='Close',
                                command=self.invalidDiag.destroy).grid(row=2, column=1)

    def start(self):
        # self.invalidDiag.grab_set() #takes control over the dialog (makes it active)
        self.invalidDiag.wait_window()


class  QuitDialog():

    def __init__(self, ):
        self.quitDialog = tk.Toplevel()
        warnMessage = tk.Label(master=self.quitDialog,
                                text='Are you sure that you want to quit? ').grid(row=1, column=1)
        cancelButton = tk.Button(master= self.quitDialog ,
                                text='Cancel',
                                command = self.quitALL).grid(row=2, column=1)

    def start(self):
        # self.invalidDiag.grab_set() #takes control over the dialog (makes it active)
        self.quitDialog.wait_window()

    def quitALL(self):

        self.quitDialog.destroy()
        tc =TimeConverter()
        tc.destroyit()



class TimeConverter:
    def __init__(self):
        self.mainWindow = tk.Tk()
        self.mainWindow.title("Seconds Converter")
        self.results = tk.StringVar()
        self.inputSecs = tk.StringVar()
        secLabel = tk.Label(master=self.mainWindow,
                            text="Seconds:").grid(row=0, sticky="W")
        resultLabel = tk.Label(master=self.mainWindow,
                               text="Converted Time:\n(H:M:S)").grid(row=1, sticky="W")
        calcResults = tk.Label(master=self.mainWindow,
                               background='light gray', width=20,
                               textvariable=self.results,
                               anchor="w").grid(row=1, column=1)
        secEntry = tk.Entry(master=self.mainWindow,
                            width=24,
                            textvariable=self.inputSecs).grid(row=0, column=1)

        calcButton = tk.Button(master=self.mainWindow,
                               text='Calculate',
                               command=self.SecondsToHours).grid(row=2,
                                                                 column=0, sticky="w")
        # quitButton = tk.Button(master=self.mainWindow,
        #                        text='Quit',
        #                        command=self.mainWindow.destroy).grid(row=2, column=1, sticky="E")
        quitButton = tk.Button(master=self.mainWindow,
                               text='Quit',
                               command=self.showQuitDialog).grid(row=3, column=1, sticky="E")

    def invalidInputEntered(self):
        errorDiag = AlertDialog()
        errorDiag.start()

    def showQuitDialog(self):
        quitdialog = QuitDialog()
        quitdialog.start()


    def startDisplay(self) -> None:
        self.mainWindow.mainloop()

    def destroyit(self):
        self.mainWindow.destroy()

    def SecondsToHours(self):
        try:
            inputseconds = int(self.inputSecs.get())
            seconds = int(inputseconds % 60)
            minutes = int(((inputseconds - seconds) / 60) % 60)
            hours = int((((inputseconds - seconds) / 60) - minutes) / 60)
            tempResults = str(hours) + ':' + str(minutes) + ':' + str(seconds)
            self.results.set(tempResults)
            return

        except ValueError:
            self.invalidInputEntered()
            #self.showQuitDialog()


if __name__ == '__main__':
    TimeConverter().startDisplay()

您在這里導入 tkinter 2 次。 一次帶有*和一個作為 tk。

只需使用:

import tkinter as tk

這將幫助您避免覆蓋其他庫導入的任何內容或讓 tkinter 的函數被其他導入覆蓋。

您有一種非常非正統的方式來創建您的 tkinter 應用程序,但如果您希望保持一切原樣,則需要更改:

讓我們從您的quitDialog window 中刪除取消按鈕,然后添加一個是和否按鈕。 這將服務器允許您說“ yes ”以銷毀所有 windows,或者說“ no ”僅銷毀quitDialog window。

首先,我們需要向您的QuitDialog class 添加一個參數,這樣我們就可以將任何 window 或我們想要的框架傳遞給它。

因此,將實例參數添加到您的QuitDialog() class 中,如下所示:

class  QuitDialog():

    def __init__(self, instance):
        self.instance = instance

現在替換:

cancelButton = tk.Button(master= self.quitDialog ,
                                text='Cancel',
                                command = self.quitALL).grid(row=2, column=1)

和:

quitButton = tk.Button(master= self.quitDialog ,
                       text='Yes', command = self.quitALL).grid(row=2, column=1)
cancelButton = tk.Button(master= self.quitDialog,
                         text='No', command = lambda: self.quitDialog.destroy()).grid(row=2, column=2)

然后讓我們將您的quitALL()方法更改為:

def quitALL(self):
    self.quitDialog.destroy()
    self.instance.destroy()

這將使用我們的實例參數來銷毀我們傳入的 window。

現在將您的showQuitDialog()方法更改為:

def showQuitDialog(self):
    quitdialog = QuitDialog(self.mainWindow)
    quitdialog.start()

如您所見,我們現在將 tk window self.mainWindowQuitDialog class,因此我們可以決定天氣或不關閉它。

下面是您的代碼的復制過去版本,它應該可以根據您的需要工作:

import tkinter as tk
from tkinter import ttk
import tkinter.messagebox
import datetime


class AlertDialog:

    def __init__(self):

        self.invalidDiag = tk.Toplevel()
        invalidInput = tk.Label(master=self.invalidDiag,
                                text='Error: Invalid Input').grid(row=1, column=1)
        closeButton = tk.Button(master=self.invalidDiag,
                                text='Close',
                                command=self.invalidDiag.destroy).grid(row=2, column=1)

    def start(self):
        # self.invalidDiag.grab_set() #takes control over the dialog (makes it active)
        self.invalidDiag.wait_window()


class  QuitDialog():

    def __init__(self, instance):

        self.instance = instance

        self.quitDialog = tk.Toplevel()

        warnMessage = tk.Label(master=self.quitDialog,
                                text='Are you sure that you want to quit? ').grid(row=1, column=1, columnspan=2)
        quitButton = tk.Button(master= self.quitDialog ,
                                text='Yes',
                                command = self.quitALL).grid(row=2, column=1)
        cancelButton = tk.Button(master= self.quitDialog,
                                text='No',
                                command = lambda: self.quitDialog.destroy()).grid(row=2, column=2)

    def start(self):
        # self.invalidDiag.grab_set() #takes control over the dialog (makes it active)
        self.quitDialog.wait_window()

    def quitALL(self):
        self.quitDialog.destroy()
        self.instance.destroy()


class TimeConverter:

    def __init__(self):

        self.mainWindow = tk.Tk()
        self.mainWindow.title("Seconds Converter")
        self.results = tk.StringVar()
        self.inputSecs = tk.StringVar()
        secLabel = tk.Label(master=self.mainWindow,
                            text="Seconds:").grid(row=0, sticky="W")
        resultLabel = tk.Label(master=self.mainWindow,
                               text="Converted Time:\n(H:M:S)").grid(row=1, sticky="W")
        calcResults = tk.Label(master=self.mainWindow,
                               background='light gray', width=20,
                               textvariable=self.results,
                               anchor="w").grid(row=1, column=1)
        secEntry = tk.Entry(master=self.mainWindow,
                            width=24,
                            textvariable=self.inputSecs).grid(row=0, column=1)

        calcButton = tk.Button(master=self.mainWindow,
                               text='Calculate',
                               command=self.SecondsToHours).grid(row=2,
                                                                 column=0, sticky="w")
        quitButton = tk.Button(master=self.mainWindow,
                               text='Quit',
                               command=self.showQuitDialog).grid(row=3, column=1, sticky="E")

    def invalidInputEntered(self):
        errorDiag = AlertDialog()
        errorDiag.start()

    def showQuitDialog(self):
        quitdialog = QuitDialog(self.mainWindow)
        quitdialog.start()

    def startDisplay(self) -> None:
        self.mainWindow.mainloop()

    def destroyit(self):
        self.mainWindow.destroy()

    def SecondsToHours(self):
        try:
            inputseconds = int(self.inputSecs.get())
            seconds = int(inputseconds % 60)
            minutes = int(((inputseconds - seconds) / 60) % 60)
            hours = int((((inputseconds - seconds) / 60) - minutes) / 60)
            tempResults = str(hours) + ':' + str(minutes) + ':' + str(seconds)
            self.results.set(tempResults)
            return

        except ValueError:
            self.invalidInputEntered()
            #self.showQuitDialog()

if __name__ == '__main__':
    TimeConverter().startDisplay()

有趣的問題。 據我所知,您也可以使用 quit() 通過關閉所有內容來退出程序。

退出()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM