0

我试图通过按下现有窗口的按钮来调用新窗口。创建新窗口时,原始窗口应关闭。当我按下按钮时,新窗口将按预期显示,但还会出现一个空白窗口。使用tk.Tk()ortk.Toplevel()将导致相同的结果。

稍后在程序中我想再次销毁创建的窗口。当使用鼠标关闭空白窗口时,当该方法应用于新窗口tk.Tk()时会产生错误“应用程序已被破坏” 。destroy()

import tkinter as tk
from tkinter import messagebox


def main():

    root = tk.Tk()
    root.title("Hauptmenü")

    Menue = MainMenue(root)
    Menue.pack()

    root.mainloop()


class MainMenue(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent)

        self.button_rennen = tk.Button(self, text="New Window", width=20, command=self.call_bet)
        self.button_rennen.pack()

    def call_bet(self):
        self.destroy()
        root2 = tk.Tk()
        Bet = BetFrame(root2)
        Bet.pack()



class BetFrame(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent)

        self.button = tk.Button(text="Wette platzieren",
                           command=self.question)

        self.button.pack()


    def question(self):
        dialog = tk.messagebox.askokcancel(message="Destroy Window?")

        if dialog is True:
            self.destroy()


main()

我正在为每个新窗口创建一个新类,因为原始程序应该返回一些变量。我知道这个话题已经有很多问题了,但对我来说,这些问题似乎都不太适合并帮助我找到解决问题的方法。我很感激任何帮助!

4

1 回答 1

0

看这个:

import tkinter as tk
from tkinter import messagebox


class MainMenue(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent)

        self.button_rennen = tk.Button(self, text="New Window", width=20,
                                       command=self.call_bet)
        self.button_rennen.pack()

    def call_bet(self):
        # `self.master` is the window
        Bet = BetFrame(self.master)
        Bet.pack()
        self.destroy()


class BetFrame(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent)

        # You need to tell the button that its master should be this BetFrame
        # If you don't it will assume you mean the window so
        # `self.destroy()` isn't going to destroy the button.
        self.button = tk.Button(self, text="Wette platzieren", command=self.question)
        self.button.pack()

    def question(self):
        dialog = tk.messagebox.askokcancel(message="Destroy Window?")

        if dialog is True:
            self.destroy()

def main():
    root = tk.Tk()

    Menue = MainMenue(root)
    Menue.pack()

    root.mainloop()


main()

您的代码很棒,但有两个错误:

  • 与其创建新窗口,不如重用旧窗口。
  • BetFrame类中创建按钮时,您不会为主参数(第一个参数)传递任何内容。这就是为什么当您使用销毁BetFrame对象时按钮不会被销毁的原因self.destroy()
于 2021-05-31T12:28:32.810 回答