如何关闭tkinter上的上一个窗口?

2024-09-29 21:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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,所以我知道这可能非常简单。谢谢你的帮助


Tags: texttitleplacelabeltkdageometrydestroy
1条回答
网友
1楼 · 发布于 2024-09-29 21:28:42

我看到几个问题。主要的一点是您不能调用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()(和pack()grid())总是返回None,这就是变量最终得到的值-这永远不是您想要的。你在这里侥幸逃脱,但只是因为那些名字不再被引用

相关问题 更多 >

    热门问题