单击按钮后如何在 tkinter 中仅打开 1 个新窗口?

问题描述

我参考了这篇文章 Python tkinter: How can I ensure only ONE child window is created onclick and not a new window every time the button is clicked?,但我的代码无法运行。有人可以帮我吗?

from tkinter import *
import os
import sys
import _thread
from s2 import work
from s1 import work2

root = Tk()
root.resizable(width=False,height=False)
root.title("Sample tkinter")
root.geometry(r"550x550")


def open_entry():
    os.system("data1.py")


def open_aisle():
    os.system("data2.py")

def close_entry():
    os.system("data10.py")

def close_aisle():
    os.system("data20.py")

def run():
    _thread.start_new_thread(work,())
    _thread.start_new_thread(work2,())

def openNewWindow():
    global createdb_btn
    newWindow = Toplevel(root)
    newWindow.resizable(width=False,height=False)
    newWindow.title("New Window")
    newWindow.geometry("300x300")
    create_front = Button(newWindow,text="Entry DB",relief=FLAT,bg="black",fg="white",command=open_entry)
    create_front.place(x=50,y=80)

    create_aisle = Button(newWindow,text="Aisle DB",command=open_aisle)
    create_aisle.place(x=145,y=80)



def openAnotherWindow():
    global removedb_btn
    otherWindow = Toplevel(root)
    otherWindow.resizable(width=False,height=False)
    otherWindow.title("New Window")
    otherWindow.geometry("300x300")
    remove_front = Button(otherWindow,command=close_entry)
    remove_front.place(x=50,y=80)

    remove_aisle = Button(otherWindow,command=close_aisle)
    remove_aisle.place(x=145,y=80)

    removedb_btn = Button(root,text="Remove databases",state=disABLED)
    removedb_btn.place(x=380,y=120)


camera_btn = Button(root,text="Open Cams",command=run)
camera_btn.place(x=50,y=120)

createdb_btn = Button(root,text="Create databases",command=openNewWindow)
createdb_btn.place(x=205,y=120)

removedb_btn = Button(root,command=openAnotherWindow)
removedb_btn.place(x=380,y=120)

root.mainloop()

我试图在 openNewWindow 函数和 openAnotherWindow 函数中实现这一点。

解决方法

这就是我所做的。更改了行:

createdb_btn = Button(root,text="Create databases",relief=FLAT,bg="black",fg="white")
createdb_btn.config(command=lambda b=createdb_btn: (openNewWindow(b),b.config(state='disabled')))

并添加

newWindow.protocol("WM_DELETE_WINDOW",lambda:(button.config(state='active'),newWindow.destroy()))

newWindow 函数内部,这样当您将创建窗口的按钮作为变量传入并在 opennewWindows 函数的覆盖上使用它以在 newWindow.destroy() 之前重新激活它

>