0

这是我的代码。当我按下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()

谢谢,我是新手,所以请帮助我。

4

1 回答 1

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()
于 2017-11-10T10:58:03.533 回答