如何限制TopLevel Window Python Tkinter的数量

时间:2017-11-10 10:34:25

标签: python tkinter window toplevel

这是我的代码。 当我按 CTRL + S 时,它会弹出一个TopLevel窗口。但是,当我再次按 CTRL + S 时,会弹出另一个窗口,依此类推。

如何改进代码,以便在按 CTRL + S 时只弹出一个窗口。

from tkinter import *
from tkinter import messagebox

class MainWindow(Frame):

    def __init__(self, master = None):
        Frame.__init__(self, master)

        self.master = master

        self.master.title("Tournament Software")

        self.menu()

    def menu(self):

        menu = Menu(self.master)
        self.master.config(menu=menu)

        participant = Menu(menu, tearoff=False)
        participant.add_command(label="Add participant", accelerator="Ctrl+S", command=self.addparticipant_window)
        menu.add_cascade(label="Participants", menu=participant)

        self.bind_all('<Control-s>', lambda e: menu.after(100,self.addparticipant_window))

    def addparticipant_window(self):
        participantWindow = Toplevel()
        participantWindow.geometry("400x350")
        participantWindow.resizable(False, False)

        top_frame = Frame(participantWindow, bg='cyan', width=450, height=50, pady=3)
        top_frame.grid(row=0, sticky="ew")

root = Tk()
root.iconbitmap("Icon.ico")
root.geometry("500x400")
root.resizable(False, False)


app = MainWindow(root)

root.mainloop()

谢谢,我是新来的,所以请帮助我。

1 个答案:

答案 0 :(得分:2)

from tkinter import *
from tkinter import messagebox

class MainWindow(Frame):

    def __init__(self, master = None):
        Frame.__init__(self, master)

        self.master = master

        self.master.title("Tournament Software")

        self.menu()
        self.popup = None

    def open_up(self):
        if self.popup is None or not self.popup.top.winfo_exists():
            self.popup = addparticipant_window()
        else:
            self.popup.top.lift(self.master)

    def menu(self):

        menu = Menu(self.master)
        self.master.config(menu=menu)

        participant = Menu(menu, tearoff=False)
        participant.add_command(label="Add participant", accelerator="Ctrl+S", command=self.open_up)
        menu.add_cascade(label="Participants", menu=participant)

        self.bind_all('<Control-s>', lambda e: menu.after(100,self.open_up))

class addparticipant_window:

    def __init__(self):
        self.top = Toplevel()
        self.top.geometry("400x350")
        self.top.resizable(False, False)

        top_frame = Frame(self.top, bg='cyan', width=450, height=50, pady=3)
        top_frame.grid(row=0, sticky="ew")

root = Tk()
root.geometry("500x400")
root.resizable(False, False)


app = MainWindow(root)

root.mainloop()