You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac环境下使用tkinter的mainloop()时窗口关闭问题求助

Fixing Tkinter Window Closing Immediately in Spyder (macOS)

Hey there! Let's break down why your Tkinter window is closing right away and how to fix it:

1. Fix the Critical Typo in Your Code

First off, there's a spelling mistake in your requests handling that's causing your program to crash before the Tkinter window even gets a chance to show up:

  • You wrote a.enconding = a.apparent_encoding — it should be a.encoding (missing one 'c').
  • This typo throws an AttributeError, which stops the entire script dead in its tracks.

Also, your regex uses &lt; (HTML escape for <), which won't match the actual < characters in the webpage source. Swap that out for a literal < to make your regex work properly.

Here's your corrected code to test:

import requests
import re
import tkinter as tk

url = 'http://www.qmaile.com/'
a = requests.get(url)
a.encoding = a.apparent_encoding  # Fixed spelling
b = a.text
reg = re.compile('<option value="(.*?)" selected="">')  # Use literal < instead of &lt;
res = re.findall(reg, b)

root = tk.Tk()
root.title("My First Tkinter Window")  # Added a title to make it easy to spot
root.mainloop()

2. Adjust Spyder's Graphics Backend Setting

Spyder's default IPython console settings can sometimes interfere with Tkinter's main loop. Here's how to tweak it:

  • Open Spyder, go to Tools → Preferences
  • Navigate to IPython console → Graphics
  • Change the Backend dropdown from Automatic to Tkinter
  • Click Apply → OK, then restart Spyder

This ensures Spyder uses Tkinter's native backend to render your GUI window, preventing it from closing prematurely.

3. Quick Debugging Trick (If Needed)

If you still run into issues, you can add a prompt after the main loop to keep the script alive (though this shouldn't be necessary if the above fixes work):

root.mainloop()
input("Press Enter to close the program...")

Give these steps a try — your Tkinter window should stay open as expected!

内容的提问来源于stack exchange,提问作者fyddward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:30:44