Python Tkinter如何实现按钮多次点击仅打开1个新窗口
问题根因
newWindow是函数内部的局部变量,首次创建窗口后,后续触发按钮点击时无法访问到已创建的窗口实例,状态判断逻辑会直接报错- 计数器逻辑没有和窗口的销毁事件绑定,窗口手动关闭后计数器不会自动重置,导致后续无法再次打开新窗口
修正方案
直接用全局变量存储窗口实例,每次点击先判断实例是否存在、是否处于存活状态,不存在才新建,存在则直接将已打开的窗口前置展示,同时绑定窗口销毁事件自动重置实例变量。
修正后的完整代码如下:
from tkinter import * window = Tk() # 用全局变量存储窗口实例,初始为None new_window = None def openNewWindow(): global new_window # 判断窗口是否已经存在且未被销毁 if new_window is not None and new_window.winfo_exists(): # 已存在则直接拉到最前 new_window.lift() return # 不存在则新建窗口 new_window = Toplevel(window) new_window.title("test ©") new_window.geometry("800x800") new_window.iconbitmap('icon4.ico') # 绑定窗口销毁事件,关闭时重置全局变量 new_window.protocol("WM_DELETE_WINDOW", lambda: destroy_new_window()) def destroy_new_window(): global new_window new_window.destroy() new_window = None width = window.winfo_screenwidth() height = window.winfo_screenheight() window.geometry("%dx%d" % (width, height)) bg = PhotoImage(file="bsor.gif") label_image = Label(window, image=bg) label_image.place(x=0, y=0) title_label = Label(window, text="Job Management System", bg="black", fg="white") title_label.config(font=("Courier", 70)) title_label.place(x=65, y=3) customer_database_button = Button(window, text="Customer Database", width="23", height="2", font=('Courier', 13, 'bold'), command=openNewWindow) customer_database_button.grid(row=3, column=0, pady=185, padx=(110, 0)) employee_database_button = Button(window, text="Employee Database", width="23", height="2", font=('Courier', 13, 'bold')) employee_database_button.grid(row=3, column=1, pady=10, padx=(50, 0)) job_category_button = Button(window, text="Job Category (Pricing)", width="23", height="2", font=('Courier', 13, 'bold')) job_category_button.grid(row=3, column=2, pady=10, padx=(50, 0)) quote_sale_button = Button(window, text="Quotes / Sales", width="23", height="2", font= ('Courier', 13, 'bold')) quote_sale_button.grid(row=3, column=3, pady=10, padx=(50, 0)) cash_management_button = Button(window, text="Cash Management", width="23", height="2", font= ('Courier', 13, 'bold')) cash_management_button.grid(row=3, column=4, pady=10, padx=(50, 0)) analysis_mode_button = Button(window, text="Analysis Mode", width="23", height="2", font= ('Courier', 13, 'bold')) analysis_mode_button.grid(row=3, column=5, pady=10, padx=(50, 0)) window.title('test') window.iconbitmap('icon4.ico') window.mainloop()
优化说明
- 无需额外维护计数器变量,直接通过窗口实例的存在状态判断是否需要新建
- 窗口手动关闭后会自动重置实例变量,下次点击可以正常打开新窗口
- 重复点击按钮会自动将已打开的窗口前置,符合用户操作预期
内容的提问来源于stack exchange,提问作者RazzcoSolutions
相关产品推荐
相关产品推荐

