如何限制顶层窗口的数量

2024-10-03 02:41:36 发布

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

这是我的密码。 当我按CTRL+S时,会弹出一个顶层窗口。但是,当我再次按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()

谢谢,我是新来的,所以帮帮我。你知道吗


Tags: fromimportselfmasterfalsetkinterdefroot
1条回答
网友
1楼 · 发布于 2024-10-03 02:41:36
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()

相关问题 更多 >