【问题标题】:closing all windows in python tkinter关闭python tkinter中的所有窗口
【发布时间】:2018-02-01 14:01:51
【问题描述】:

我正在使用 python 中的 tkinter 库。我有一个主窗口,其中有几个按钮,当单击这些按钮时,会弹出一个新窗口,其中还有一个名为取消的按钮。我想为所有窗口设置取消按钮。

我尝试了以下解决方案,它只关闭当前窗口。

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

【问题讨论】:

  • 欢迎来到 StackOverflow!请提供Minimal, Complete, and Verifiable example。您无需提供完整代码。足以显示您的问题的示例。其余的只是妨碍人们能够帮助你。在那张纸条上,我可以告诉您,至少在我复制粘贴代码进行测试时,您当前的代码不会打开新窗口。
  • 如果你想彻底摧毁所有的窗户,你需要在self.mainWindow上调用destroy
  • 对不起,如果我的问题不清楚。在我的 QuitDialog 类中,有一个名为取消的按钮。我希望该按钮关闭所有窗口。
  • @SamThapa:我已经更新了我的答案,如果您有任何问题,请告诉我。

标签: python tkinter python-3.5


【解决方案1】:

您在这里导入 tkinter 2 次。一次是*,一次是 tk。

只需使用:

import tkinter as tk

这将帮助您避免覆盖其他库导入的任何内容或让 tkinter 的函数被其他导入覆盖。

您有一种非常非正统的方式来创建您的 tkinter 应用程序,但如果您希望保持一切原样,您需要进行更改:

让我们从quitDialog 窗口中删除取消按钮,然后添加一个是和否按钮。这将允许您说yes 来销毁所有窗口或说no 只销毁quitDialog 窗口。

首先,我们需要为您的 QuitDialog 类添加一个参数,以便我们可以将任何我们想要的窗口或框架传递给它。

因此,将实例参数添加到您的 QuitDialog() 类中,如下所示:

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

这将使用我们的实例参数来销毁我们传入的窗口。

现在将您的 showQuitDialog() 方法更改为:

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

如您所见,我们现在将 tk 窗口 self.mainWindow 传递给 QuitDialog 类,以便我们决定天气或不关闭它。

下面是您的代码的复制过去版本,它应该可以根据您的需要工作:

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

【讨论】:

  • 非常感谢。你是救生员。
  • @SamThapa 如果此答案对您有用,请考虑选中我的答案旁边的复选标记。
猜你喜欢
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 2017-09-04
  • 1970-01-01
相关资源
最近更新 更多