Tkinter 在项目目录中看不到文件,即使 os.path.exists() 在项目目录中可以看到文件

Tkinter doesn't see file in project directory even though os.path.exists() does

提问人:warmike_1 提问时间:5/20/2023 更新时间:5/20/2023 访问量:29

问:

我在 Tkinter 中为我的按钮提供了 PNG 图标,选择正确按钮的函数如下所示:

def square_pic(b: chess.board, i: int, j: int):
    square = b.board_state[i][j]
    color = (i + j) %2
    if square.s_piece !=0:
        return "{0}_{1}_{2}.PNG".format(square.s_piece, square.s_color, color)
    else:
        return "0_{0}".format(color) 

创建带有图标的按钮的代码如下所示:

            photo = square_pic(b, i, j)
            print(os.path.exists(photo))
            t=Button(root, height=40, width=40, image=photo)
            t.grid(row=7-i,column=j, sticky=W) 

它将“True”打印到控制台,但抛出异常“图像”4_0_1.PNG“不存在”。为什么 tkinter 看不到图像?如果重要的话,我正在使用 Python 3.9 和 Visual Studio 2022。

Python visual-studio 图像 文件 tkinter

评论

2赞 JonSG 5/21/2023
尝试使用photo = PhotoImage(file=photo)
3赞 Sylvester Kruin - try Codidact 5/21/2023
如 JonSG 所示,您需要使用 a 在 中创建一个图像。现在,你给出的是图像的路径,而不是实际图像本身。PhotoImagetkinterButton

答: 暂无答案