Tkinter创建单个窗口却弹出额外窗口的问题排查
问题原因分析
- 额外窗口弹出:代码最后调用了
mainloop()而非root.mainloop(),Tkinter中直接调用mainloop()会自动创建一个默认根窗口实例,加上手动创建的root = Tk(),就会出现两个窗口。 - 窗口重启、闪烁:重复实例化
ttk.Style并重复配置样式,再加上默认窗口和手动创建窗口的事件循环冲突,导致窗口状态异常,出现闪烁或重启现象。另外,空的root.configure()调用属于无效代码,无实际作用。
修复后的代码
# Modules from tkinter import * from tkinter import ttk # Functions def information(): pass def main_page(): pass # Main Window root = Tk() root.title("iHealthy") root.iconbitmap("iHealthy.ico") window_width = 500 window_height = 400 root.config(bg="white") root.resizable(False, False) screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() center_x = int(screen_width / 2 - window_width / 2) center_y = int(screen_height / 2 - window_height / 2) root.geometry(f"{window_width}x{window_height}+{center_x}+{center_y}") # 仅初始化一次Style并配置 style = ttk.Style() style.configure("TButton", background="white", foreground="black", padding=15, font=("Arial", 10)) # Script root.columnconfigure(0, weight=2) root.columnconfigure(1, weight=2) root.columnconfigure(2, weight=2) root.columnconfigure(3, weight=2) information_page = ttk.Button(root, text="Take Tour", command=lambda: information()) home_page = ttk.Button(root, text="Home Page", command=lambda: main_page()) information_page.pack() home_page.pack() # Mainloop - 指定主窗口的事件循环 root.mainloop()
关键修改点
- 将最后的
mainloop()替换为root.mainloop(),明确绑定到创建的主窗口,避免默认窗口生成。 - 移除重复的
ttk.Style实例化和配置代码,只保留一次初始化配置。 - 删除无意义的
root.configure()空调用。
内容的提问来源于stack exchange,提问作者Jessica Julia
相关产品推荐
相关产品推荐

