点击按钮后清空Tkinter窗口(不关闭)无响应问题排查
问题解决:Tkinter点击按钮无法清空窗口
你的代码里clearScreen函数用了grid_slaves()来获取控件,但你所有的控件(Label和Button)都是用place()布局的,grid_slaves()只能识别用grid()布局的控件,所以点击按钮后没有任何反应。
修复方案
把grid_slaves()替换成winfo_children(),这个方法能获取窗口下的所有子控件,无论使用哪种布局方式。修改后的clearScreen函数如下:
# Clear screen function # def clearScreen(object): screenItem = object.winfo_children() for i in screenItem: i.destroy() # --------------------- #
完整修改后的代码
# IMPORTS # import tkinter as tk # ------- # # Define Window # window = tk.Tk() window.title("Bioinformatics Showcase") window.geometry("600x400") # ------------- # # Clear screen function # def clearScreen(object): screenItem = object.winfo_children() for i in screenItem: i.destroy() # --------------------- # # Event functions # def startEvent(event): clearScreen(window) # ------- # # Create Welcome Page # welcomeLabel = tk.Label(text="Welcome, User! :3") welcomeLabel.place(relx = .5, rely = .1, anchor = "center") # Make start button startButton = tk.Button(window, text = "Click here to start") startButton.place(relx = .5, rely = .5, anchor = "center") # Bind button to start event startButton.bind("<Button-1>", startEvent) # <Button-1> is the mouse left click # ------------------- # # Main loop keeps window open until user closes it # window.mainloop()
额外优化建议
按钮绑定事件可以直接用command参数,比bind更简洁,修改按钮部分代码:
startButton = tk.Button(window, text = "Click here to start", command=lambda: clearScreen(window))
这样可以去掉startEvent函数,代码更精简。
内容的提问来源于stack exchange,提问作者Mell
相关产品推荐
相关产品推荐

