如何关闭由函数创建的新窗口

时间:2019-05-01 21:39:11

标签: python-3.x tkinter tkinter-canvas

我有一个tkinter UI,其中有一个框架,该框架有2个画布,一个画布有一个按钮,可创建一个顶层窗口(名为top)。该顶层窗口具有一个CLOSE按钮,用于关闭顶层窗口(可通过top.destoy轻松完成)。但是,我需要“关闭”按钮才能调用执行某项功能的函数。因此,由于无法将CLOSE按钮配置为调用something()和destroy(),因此我将按钮设置为调用sequence(),后者又调用something()和top.destroy()。

运行此命令并单击“关闭”按钮时,出现错误名称“ top”未定义。我知道为什么会这样,但是我不知道该如何解决。有什么想法吗?

import time
import tkinter as tk
import tkinter.font
from tkinter import*

window = Tk()
window.geometry("1920x1080")
window.title("HOME")

f1 = Frame (window, bg="white")
f1.pack()

c1 = Canvas(f1, height=200, width=1960, bg="white")
label = Label(f1, text="Running Apps", font= "Cambria 30 bold").pack()
c1.pack(anchor=N)

r = c1.create_rectangle(400, 50, 550, 150, fill="white", activefill="black")
r2 = c1.create_rectangle(550, 50, 700, 150, fill="white", activefill="black")

c2 = tk.Canvas(f1, height=800, width=1960,  bg="white")
c2.pack(side="bottom")

def sequence():
    top.destroy()
    c1.itemconfig(r, fill="white")  #something()


def openApp1():
    c1.itemconfig(r, fill="red")
    top = Toplevel()
    top.geometry("1920x1080")
    top.title("App 1")

    cvs1 = tk.Canvas(top, height="880", width="800", bg="red")
    Closebutton = Button(cvs1, text="CLOSE", command=sequence, padx="20", pady="0", justify="center", height="1", width="6", font="Cambria 20 bold",         borderwidth="7")
    cvs1.create_window(400, 600, window=Closebutton)
    label1 = Label(top, text="I am App 1", font= "Cambria 50 bold")
    label1.place(x=630, y=100)
    cvs1.pack()

button1= Button(c2, bg="red", text="App 1", command=openApp1, padx="20", pady="10", justify="center", height="3", width="10", font="Cambria 30 bold", borderwidth="10")
c2.create_window(100, 200, anchor=NW, window=button1)

window.mainloop()

1 个答案:

答案 0 :(得分:1)

global top中使用openApp1,它将TopLevel分配给全局变量(而不是局部变量),它将解决sequence中的问题

def openApp1():
    global top

    c1.itemconfig(r, fill="red")
    top = Toplevel()