Python导入requests模块触发AttributeError错误求助
问题
运行包含tkinter和requests库的Python代码时,导入requests失败,报错堆栈显示导入decimal模块时触发AttributeError: module 'numbers' has no attribute 'Number',完整报错信息和代码如下:
报错信息
30 Traceback (most recent call last): File "c:\Users\Lenovo\Desktop\Code fs\gui.py", line 2, in <module> import requests File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\__init__.py", line 118, in <module> from . import utils File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\utils.py", line 27, in <module> from ._internal_utils import to_native_string File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\_internal_utils.py", line 11, in <module> from .compat import is_py2, builtin_str, str File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\compat.py", line 29, in <module> import simplejson as json File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\__init__.py", line 130, in <module> from decimal import Decimal File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\decimal.py", line 3, in <module> from _decimal import * AttributeError: module 'numbers' has no attribute 'Number'
代码
import tkinter as tk import requests import json def jprint(obj): text = json.dumps(obj, sort_keys=True, indent=4) print(text) window = tk.Tk() window.geometry("900x550") window.title("Yo mama") window.grid_columnconfigure(0, weight=1) def yomama(): response = requests.get("https://api.yomomma.info/") jprint(response.json()) welcome_label = tk.Label(window, text="Welcome! Click the button to get a extreamly funny yo mama joke", font=("Helvetica", 15)) welcome_label.grid(row=0, column=0, sticky="N", padx=20, pady=10) button = tk.Button(text="Get spicy yo mama joke", command=yomama) button.grid(row=1, column=0, sticky="WE", padx=10, pady=10) if __name__ == "__main__": window.mainloop()
排查与解决方法
这个错误的核心原因是Python标准库的numbers模块被破坏或被同名文件覆盖,导致decimal模块依赖的numbers.Number无法正常访问。按以下步骤修复:
检查并移除同名文件
查看代码所在的c:\Users\Lenovo\Desktop\Code fs\目录下,是否存在名为numbers.py的文件。如果有,直接删除或重命名(比如改成my_numbers.py),避免覆盖系统标准库模块。修复损坏的标准库
如果目录中没有同名文件,说明numbers模块本身已损坏。重新安装Python 3.9:- 卸载当前Python 3.9版本
- 下载对应版本的官方安装包重新安装
- 安装完成后,执行
pip install requests重新安装requests库
验证修复结果
打开Python交互环境,输入以下命令测试:import numbers print(numbers.Number)若能正常输出
<class 'numbers.Number'>,说明模块已恢复,再运行你的代码即可。
内容的提问来源于stack exchange,提问作者Gamer555DT
相关产品推荐
相关产品推荐

