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

运行login.py调用main.py时提示文件不存在的技术问询

问题描述

目录结构如下:

CTK/
├── assets/
│   └── images/
│       └── [图片文件]
├── view/
│   └── main.py
└── login.py

通过login.py中的show_main函数调用main.py时,尽管指定了文件路径,仍出现文件找不到错误。

main.py 代码

import os
from PIL import Image
import customtkinter as ctk

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # 向上跳转1层目录进入CTK
assets_dir = os.path.join(base_dir, 'assets', 'images')  # 构造图片目录路径

# 加载图片函数
def load_image(filename, size):
    image_path = os.path.join(assets_dir, filename)
    try:
        image = Image.open(image_path).resize(size)
        return ctk.CTkImage(image, size=size)
    except FileNotFoundError:
        print(f"File not found: {image_path}")
        raise  # 重新抛出错误终止程序

login.py 代码

def show_main():
    try:
        # 销毁前检查app是否已初始化
        if app:
            app.destroy()
        from View import main # 此处导入可能引发循环导入问题
    except Exception as e:
        print(f"show_main函数中出错: {e}")

报错信息

C:\Users\admin\AppData\Local\Microsoft\WindowsApps\python3.11.exe C:\Users\admin\Documents\skype\CTK\login.py
成功连接到MySQL数据库
[{'user_id': 14, 'username': 'bim', 'password_hash': '20d8c276b8e9801568963497d299f2501dc18f078ca95b4a555d8646e7af720c', 'email': 'bim@gmail.com', 'created_at': datetime.datetime(2024, 10, 1, 20, 23)}]
invalid command name "1374820852736update"
while executing
"1374820852736update"
("after" script)
invalid command name "1374820974400check_dpi_scaling"
while executing
"1374820974400check_dpi_scaling"
("after" script)
invalid command name "1374856334464_click_animation"
while executing
"1374856334464_click_animation"
("after" script)
show_main函数中出错: [Errno 2] No such file or directory: '../assets/images/search.png'
解决方案

1. 修复导入路径大小写问题

你的目录名是view(小写),但导入代码里写的是from View import main(大写),这会导致导入失败,进而触发后续路径错误。修改导入语句为:

from view import main

2. 验证路径正确性

在main.py开头添加打印语句,确认计算出的路径是否匹配实际文件位置:

print("Base directory:", base_dir)
print("Assets directory:", assets_dir)

运行后检查输出路径是否和CTK/assets/images的绝对路径一致。

3. 解决循环导入问题

如果main.py也导入了login.py,会触发循环导入。可以保持当前的函数内延迟导入方式,或者把共享逻辑抽离到单独模块(比如utils.py),避免互相导入。

4. 处理Tkinter的"after"脚本错误

销毁窗口后,之前通过after注册的回调仍在执行,导致无效命令错误。在销毁窗口前取消所有未执行的after任务:

if app:
    app.after_cancel("all")
    app.destroy()

内容的提问来源于stack exchange,提问作者NGỌ MẬU HOÀNG ĐỨC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 17:31:05