【发布时间】:2016-03-23 18:16:02
【问题描述】:
我正在 tkinter 上创建一个纸牌游戏,我想将文件保存在一个子文件夹中,如下所示:
/
|-card_game.py
|-mypackages
|-anyrandomstuff
|-foo.py
|-spam.py
|-cards
|-heart7.gif
|-heart8.gif
|-heart9.gif #and so on all 32 cards of a standart card game
我知道如何在 tkinter 中显示图像,但前提是它们与 card_game.py 处于完全相同的级别。由于我不希望文件夹中出现这样的混乱,我开始对 google 和 Stackoverflow 进行研究。我没有得到任何结果,所以我尝试了一些不同的方法:
from tkinter import *
main = Tk()
photo = PhotoImage(file='mypackages/cards/heart8.gif')#Here I tried: '.','\\','/', no results
photo_label = Label(image=photo)
photo_label.grid()
photo_label.image = photo
main.mainloop()
这是错误信息,我理解得很好,但我不知道如何解决问题
Traceback (most recent call last):
File "root\mypackages\cards\heart7.py", line 5, in <module>
photo = PhotoImage(file='mypackages/cards/heart7.gif')
File "Python\Python35-32\lib\tkinter\__init__.py", line 3393, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "Python\Python35-32\lib\tkinter\__init__.py", line 3349, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "mypackages/cards/heart8.gif": no such file or directory
什么是“告诉”python 你想要子文件夹中的图像的正确方法是什么?
【问题讨论】:
-
.../cards/heart7.py是您的主要可执行文件,您运行的文件吗? -
如果您知道绝对路径,则可以使用绝对路径,但回溯表明您正在尝试从
.../cards/heart7.py文件初始化卡,在这种情况下,它位于同一文件夹中,您可以使用 @ 987654328@ -
您忘记了斜杠,应该是 file='/mypackages/cards/heart8.gif' 但可以取决于您的操作系统并假设“mypackages”上方没有目录,尽管这里它说您还应该在
中包含“root”文件“root\mypackages\cards\heart7.py”,第 5 行 -
@Curly Joe:我试过了,它给了我和以前一样的错误
-
那么这不是完整的路径。您必须使用完整路径。查看 os.getcwd() 打印的内容docs.python.org/2/library/os.html#os-file-dir
标签: python image python-3.x tkinter