首页 > 解决方案 > 如何关闭 tkinter 上的上一个窗口?

问题描述

当我单击按钮转到下一个窗口时,我正在尝试关闭上一个窗口。我做不到。怎么了?

from tkinter import *

def newwindow2():
    newwindow.destroy()
    newwindow2 = tk.Toplevel()
    newwindow2.title('Nível da grama região 3')
    newwindow2.geometry('580x520')
    labl3 = Label(newwindow2, text='A foto do nível da grama na região 3 foi tirada:  \n', font=30).place(x=110, y=10)
    tk.Button(newwindow2, text='Fim').place(x=250, y=470)

def newwindow():
    janela1.destroy()
    newwindow = tk.Toplevel()
    newwindow.title('Nível da grama região 2')
    newwindow.geometry('580x520')
    labl2 = Label(newwindow, text='A foto do nível da grama na região 2 foi tirada:  \n', font=30).place(x=110, y=10)
    tk.Button(newwindow, text='Próximo', command=newwindow2).place(x=250, y=470)


janela1 = tk.Tk()
janela1.title('Nível da grama região 1')
janela1.geometry("580x520")
labl1=Label(janela1, text='A foto do nível da grama na região 1 foi tirada: ',font=30).place(x=110, y=10)
tk.Button(janela1, text='Próximo', command=newwindow).place(x=250, y=470)

janela1.mainloop()

如您所见,我正在尝试使用 .destroy() 但它不起作用。有什么解决办法吗?我刚开始学习 Python,所以我知道这可能非常简单。谢谢您的帮助!

标签: pythonpython-3.xtkintertoplevel

解决方案


我看到了几个问题。主要的是你不能调用newwindow.destroy(),因为newwindow它是一个函数而不是一个tk.Toplevel小部件。另一个是janela1.destroy()破坏本身,它是根窗口。

withdraw()您可以只使用它们,而不是破坏窗户。这是我认为可以满足您要求的代码:

from tkinter import *
import tkinter as tk

def make_newwindow2():
#    newwindow.destroy()
    global newwindow2

    newwindow.withdraw()
    newwindow2 = tk.Toplevel()
    newwindow2.title('Nível da grama região 3')
    newwindow2.geometry('580x520')
    labl3 = Label(newwindow2,
                  text='A foto do nível da grama na região 3 foi tirada:\n', font=30)
    labl3.place(x=110, y=10)
    tk.Button(newwindow2, text='Fim', command=root.quit).place(x=250, y=470)

def make_newwindow():
#    janela1.destroy()
    global newwindow

    root.withdraw()
    newwindow = tk.Toplevel()
    newwindow.title('Nível da grama região 2')
    newwindow.geometry('580x520')
    labl2 = Label(newwindow,
                  text='A foto do nível da grama na região 2 foi tirada:\n', font=30)
    labl2.place(x=110, y=10)
    tk.Button(newwindow, text='Próximo', command=make_newwindow2).place(x=250, y=470)

root = tk.Tk()
root.title('Nível da grama região 1')
root.geometry("580x520")

labl1 = Label(root, text='A foto do nível da grama na região 1 foi tirada: ', font=30)
labl1.place(x=110, y=10)
tk.Button(root, text='Próximo', command=make_newwindow).place(x=250, y=470)

root.mainloop()

我改变的其他一些东西,即使它不是绝对必要的,是你如何将调用结果分配给place()小部件的名称。由于place()(and pack()and grid()) 总是 return None,这就是变量最终的值——这绝不是你想要的。你在这里侥幸逃脱,但这只是因为这些名字不再被引用。


推荐阅读