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

Python报错:main thread is not in main loop,MAC地址查询代码求助

解决Error: main thread is not in main loop问题(MAC地址查询代码)

错误原因

这个报错是因为turtle模块的GUI操作依赖自身的事件主循环,你的代码在调用turtle.textinput后没有正确处理事件循环,同时safe_input函数还存在输入参数错误。

修改后的代码

#$language = "Python3"
#$interface = "1.0"

import sys
import requests
from requests import get
import turtle

class Macpyoui:
    def __init__(self, api):
        self.api = api

def safe_input(input_message):
    if not sys.stdin:
        sc = turtle.Screen()
        sc.setup(0, 0)
        # 获取输入后关闭窗口并退出turtle事件循环
        user_input = turtle.textinput("Your App Title", input_message)
        sc.bye()
        turtle.done()
        return user_input
    # 修复原代码中input参数错误,传递正确提示信息
    return input(input_message)

site = "https://api.macvendors.com/"
data = Macpyoui(site)
macaddress = safe_input("Please enter the MAC address: ")

def searchmac():
    # 处理用户取消输入的情况
    if not macaddress:
        print("No MAC address entered.")
        return
    macsend = data.api + macaddress
    try:
        vendorsearch = get(macsend).text
        if "Not Found" in vendorsearch:
            print("MAC address not found.")
        else:
            print(vendorsearch)
    except requests.exceptions.RequestException as e:
        print(f"Request error: {e}")

if __name__ == "__main__":
    searchmac()

关键修改点

  • 在调用turtle.textinput后,添加sc.bye()关闭turtle窗口、turtle.done()退出事件循环,确保主线程回到正常执行流程,解决主循环未启动的错误。
  • 修复safe_input函数中input(str)的错误,改为传递实际提示信息input(input_message)。
  • 增加输入为空的判断,处理用户取消输入的场景。
  • 添加请求异常捕获,处理网络连接失败等异常情况。

内容的提问来源于stack exchange,提问作者Lukas J.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:43:21