简体   繁体   中英

Mac Python 3.4.4, importing files/images, tkinter

I am having difficulty displaying an image on a canvas using tkinter. I believe the problem arises from me improperly loading the image. Below is the code that I am trying to make work. The " file='Users/ramos1992/Desktop/test_image.gif' " is my attempt at loading an image from my desktop.

from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()
my_image = PhotoImage(file='Users/ramos1992/Desktop/test_image.gif')
canvas.create_image(0, 0, anchor=NW, image=my_image)

mainloop()

What is the correct method of loading files using a Mac and how can I make the code work?

The path /Users/ramos1992/Desktop/test_image.gif , which a leading slash, is an absolute path : it starts at the top of your hard disk, gets the directory named Users there, then gets the directory named ramos1992 there, and so on.

The path Users/ramos1992/Desktop/test_image.gif , without a leading slash, is a relative path : it starts in the current working directory. Which may be, say, /Users/ramos1992/Documents/Python Projects . So, you end up looking in /Users/ramos1992/Documents/Python Projects/Users/ramos1992/Desktop/test_image.gif , and of course there's no such location.

See absolute and relative paths on Wikipedia for more details.


Just in case you (or someone else reading this) was a classic Mac expert back in the old days and is confused: absolute vs. relative paths have almost the exact opposite syntax between classic Mac OS-style paths and modern Mac OS X-style (Unix) paths. The old-style Drive:Folder:Folder:File with no prefix is /Drive/Folder/Folder/File , while the old-style :Folder:File with a prefix is ./Folder/File , which is effectively the same as Folder/File , with no prefix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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