python - 如何关闭 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,所以我知道这可能非常简单。谢谢您的帮助!
解决方案
我看到了几个问题。主要的是你不能调用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
,这就是变量最终的值——这绝不是你想要的。你在这里侥幸逃脱,但这只是因为这些名字不再被引用。
推荐阅读
- html - css`位置:绝对;bottom: 0` 将 div 移动到屏幕底部而不是父级底部
- android - Gradle 依赖外部项目后备模块
- git - 通过电子邮件发送 git 项目 git security
- javascript - 使用重组组件作为参考时失去功能
- sql - 在 Sql server 中查询以下模式
- docker - kube_state 指标返回什么?
- botframework - Bot Framework 主动消息
- plot - gnuplot - 偏移 xtics
- git - 分阶段,非分阶段,未推动和未拉动。正确的工作流程?
- fabricjs - 织物。禁用所有事件/选择。(制作滴管)