Tkinter中destroy_windowroot函数未调用问题排查
Tkinter函数未调用问题排查与修复
这段代码期望每次点击按钮创建新窗口,统计点击次数,当次数超过2时关闭主窗口。目前计数功能正常,但
destroy_windowroot函数始终未被调用,请问我遗漏了什么?
用户提供的代码:
from tkinter import * count = 0 def create_window(): global count new_window = Toplevel() count += 1 if count > 2: destroy_windowroot print(count) def destroy_windowroot(): window.destroy() print("something is going on") window = Tk() b = Button(window, text="create new window dont go past 2", command=create_window) b.pack() window.mainloop()
问题原因
核心错误是函数调用的语法缺失:在create_window函数的if count > 2分支中,仅写了函数名destroy_windowroot,但没有添加括号()。函数名本身只是一个对象引用,不会触发函数的执行逻辑。
修复后的代码
from tkinter import * count = 0 def create_window(): global count new_window = Toplevel() count += 1 if count > 2: destroy_windowroot() # 添加括号,触发函数调用 print(count) def destroy_windowroot(): window.destroy() print("something is going on") window = Tk() b = Button(window, text="create new window dont go past 2", command=create_window) b.pack() window.mainloop()
效果说明
点击按钮第3次时,count变为3,满足count > 2的条件,此时会执行destroy_windowroot()函数,主窗口将被关闭,同时控制台会打印"something is going on"。
内容的提问来源于stack exchange,提问作者nuahuah
相关产品推荐
相关产品推荐

