Mac环境下使用tkinter的mainloop()时窗口关闭问题求助
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 bea.encoding(missing one 'c'). - This typo throws an
AttributeError, which stops the entire script dead in its tracks.
Also, your regex uses < (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 < 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
Backenddropdown fromAutomatictoTkinter - 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

