首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在tkinter python中打开新窗口时关闭当前窗口

在tkinter python中打开新窗口时关闭当前窗口
EN

Stack Overflow用户
提问于 2021-04-28 15:25:03
回答 1查看 528关注 0票数 1

我已经使用tkinter用Python创建了一个程序。我为两个窗口创建了两个独立的类。我正在通过单击一个窗口的按钮来打开另一个窗口。我希望当新的窗口打开时,另一个窗口应该关闭。我的代码是

代码语言:javascript
运行
复制
from tkinter import Tk, Toplevel
from tkinter import *
def main():
    main_window = Tk()
    app = first(main_window)
    main_window.mainloop()


class first:
    def __init__(self, root):
        self.root = root
        self.root.title('First window')

        self.root.geometry('1350x700+0+0')
        frame1 = Frame(self.root, bg='black')
        frame1.place(x=400, y=50, width=400, height=600)
        btn_1 = Button(frame1, command=self.second_window, text='open second window', font=("Times New Roman", 15, 'bold'), bd=3,
                           relief=RIDGE,
                           cursor='hand2', bg='red', fg='white', activeforeground='white', activebackground='red')
        btn_1.place(x=100, y=350, width=220, height=35)

    def second_window(self):
        self.new_window = Toplevel(self.root)
        self.app = second(self.new_window)


class second:
    def __init__(self, root):
        self.root = root
        self.root.title('Second Window')
        self.root.geometry("1350x700+0+0")
        self.root.config(bg='white')
        frame1 = Frame(self.root, bg='black')
        frame1.place(x=400, y=50, width=400, height=600)
        btn_1 = Button(frame1, command=self.first_window, text='open first window',
                       font=("Times New Roman", 15, 'bold'), bd=3,
                       relief=RIDGE,
                       cursor='hand2', bg='red', fg='white', activeforeground='white', activebackground='red')
        btn_1.place(x=100, y=350, width=220, height=35)

    def first_window(self):
        self.new_window = Toplevel(self.root)
        self.app = first(self.new_window)


if __name__ == '__main__':
    main()

我知道这个问题很常见,但我在这里找不到一个适用于我的代码的解决方案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-28 17:16:51

您可以使用Tk类销毁前一个窗口并启动一个新窗口

代码语言:javascript
运行
复制
from tkinter import *
from tkinter.ttk import Button
root = Tk()
root.title("title")
root.geometry("800x500")

def window2():
    root.destroy()
    window2_main = Tk()
    Label(window2_main, text="Bye Bye").pack()
    window2_main.mainloop()
a = Button(text="Click This", command=window2)
a.pack()
root.mainloop()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67295637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档