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

2024-10-01 00:33:17 发布

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

一般来说,我对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)

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


Tags: lambdatexttkintercreatecolumnbuttonwindow按钮
2条回答

尝试此操作您将需要添加window = None来初始化您的对象

window = None

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

如果您的目标是能够打开特定数量的窗口,那么考虑将这些窗口存储在列表中,然后使用^ {CD1>},您可以从存在的列表中弹出它们。

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

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()

相关问题 更多 >