Python 如何限制按钮可以打开的窗口数?

Python 如何限制按钮可以打开的窗口数?,python,tkinter,Python,Tkinter,一般来说,我对tkinter和python都是新手。我正在申请,需要一个“设置”按钮。 我就是这样创建它的: buttonSettings = Button(win, text=txtSettings, command=lambda: create_window(win)) buttonSettings.grid(row=1, column=4) 其中: def create_window(win): window = Toplevel(win) 如何将该按钮可以创建的窗口数量限制为

一般来说,我对tkinter和python都是新手。我正在申请,需要一个“设置”按钮。 我就是这样创建它的:

buttonSettings = Button(win, text=txtSettings, command=lambda: create_window(win))
buttonSettings.grid(row=1, column=4)
其中:

def create_window(win):
    window = Toplevel(win)

如何将该按钮可以创建的窗口数量限制为一个?

尝试此操作。您需要添加
窗口=无
来初始化对象

window=None
def创建_窗口(win):
如果(非窗口):
窗口=顶级(win)

<代码> > p>如果您的目标是能够打开特定数量的窗口,那么考虑将这些窗口存储在列表中,然后使用<代码>索引()/代码>您可以从现有的列表中弹出它们。

请参阅下面的示例,如果您有问题,请告诉我:

import tkinter as tk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.geometry('200x50')
        self.top_windows = []
        tk.Button(self, text='Open window!', command=self.open_top).pack()

    def open_top(self):
        if len(self.top_windows) <= 5:
            top = tk.Toplevel(self)
            self.top_windows.append(top)
            tk.Button(self.top_windows[-1], text='exit',
                      command=lambda top=top: (self.top_windows.pop(self.top_windows.index(top)), top.destroy())).pack()

App().mainloop()
将tkinter作为tk导入
类应用程序(tk.tk):
定义初始化(自):
super()。\uuuu init\uuuuu()
自几何体('200x50')
self.top_窗口=[]
按钮(self,text='Open window!',command=self.Open\u top).pack()
def打开_顶部(自):

如果len(self.top_窗口)您只希望它是1个窗口吗?如果是这样,您可以在窗口打开时禁用,然后在顶部窗口关闭时重新启用。如果有多个窗口,您可以在禁用之前运行一次检查,查看打开了多少个窗口。