简体   繁体   English

如何Python tkinter图片插入相对路径方法

[英]How to Python tkinter image insert relative path method

There's something I want to make, so I'm learning tkinter.有东西想做,所以在学习tkinter。

The relative route is not recognized.无法识别相对路径。

Example code.示例代码。 Suppose that hyunju.png is in the corresponding.py folder.假设 hyunju.png 在对应的.py 文件夹中。

import tkinter

root = tkinter.Tk()
root.title("tk")
canvas = tkinter.Canvas(root, width=400, height=600)
canvas.pack()
gazou = tkinter.PhotoImage(file="hyunju.png")
canvas.create_image(200, 300, image=gazou)
root.mainloop()

tkinter.TclError: couldn't open "hyunju.png": no such file or directory tkinter.TclError:无法打开“hyunju.png”:没有这样的文件或目录

I'm having a hard time because if I use Copy path, there will be a problem when I share or change files.我很难过,因为如果我使用复制路径,当我共享或更改文件时会出现问题。

The editor used is VS code and OS is window 10.使用的编辑器是 VS 代码,操作系统是 window 10。

help for me thank you帮我谢谢

Depending on hardcoded relative paths should be avoided in this scenario, as they're often times unreliable .在这种情况下应避免依赖硬编码的相对路径,因为它们通常是不可靠的。 Depending on your IDE and even OS it may work or not.根据您的IDE甚至操作系统,它可能工作或不工作。

Thus, You should choose a more dynamic better an approach like the following:因此,您应该选择更动态的更好的方法,如下所示:

import pathlib, os
img_file_name = "hyunju.png"
current_dir = pathlib.Path(__file__).parent.resolve() # current directory
img_path = os.path.join(current_dir, img_file_name) # join with your image's file name

As long as the image file is guaranteed to be in the same directory as the script being executed, it does not matter what IDE / OS you're on - it will work.只要保证图像文件与正在执行的脚本位于同一目录中,那么您使用的IDE / OS都没有关系 - 它会起作用。

I had the same problem and I don't know if it might be the same case for you, just check that you are opening the whole project and not just the.py file if you are working on an IDE like, for example, Visual Studio Code, because else it won't be able to find any relatives paths我遇到了同样的问题,我不知道您是否会遇到同样的情况,如果您正在处理 IDE (例如 Visual),请检查您是否打开了整个项目,而不仅仅是打开 .py 文件Studio Code,否则它将无法找到任何亲属路径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM