Mac系统下Python3显示图片的代码实现(新手求助)
Hey there! I remember struggling with this exact issue when I was starting out with Python on Mac—image display can feel tricky at first, but there are a few straightforward, reliable methods to get it working. Let’s break them down step by step:
Method 1: Using Pillow (Most Common & Simple)
Pillow is the go-to library for image handling in Python, and it works seamlessly with Mac’s system tools to display images.
First, install it if you haven’t already:
pip3 install pillow
Then use this code to load and display an image:
from PIL import Image # Replace with your image path—can be absolute (e.g., "/Users/YourName/Desktop/cat.jpg") or relative if the image is in the same folder as your script image_path = "your_image.jpg" try: img = Image.open(image_path) img.show() # This will open the image in Mac's Preview app except FileNotFoundError: print("Oops! Couldn't find the image. Double-check your file path.")
Pro tip: If you’re unsure about the path, you can drag the image from Finder into your terminal to get the full absolute path automatically.
Method 2: Using Matplotlib (Great for Visualization Workflows)
If you’re already using matplotlib for plotting, it’s easy to use it to display images too—this will show the image in a matplotlib window instead of Preview.
Install matplotlib first if needed:
pip3 install matplotlib
Here’s the code:
import matplotlib.pyplot as plt import matplotlib.image as mpimg image_path = "your_image.jpg" img = mpimg.imread(image_path) plt.imshow(img) plt.axis('off') # Hides the axis ticks/labels for a cleaner look plt.show()
Method 3: Using Tkinter (Built-in, No Extra Installs)
Mac comes with Tkinter pre-installed with Python 3, so this is a good option if you don’t want to install additional libraries. You’ll still need Pillow to handle image formats properly though:
import tkinter as tk from PIL import Image, ImageTk root = tk.Tk() root.title("Image Viewer") image_path = "your_image.jpg" img = Image.open(image_path) # Resize the image if it's too big for the window (optional) img = img.resize((500, 500), Image.Resampling.LANCZOS) tk_img = ImageTk.PhotoImage(img) label = tk.Label(root, image=tk_img) label.pack() root.mainloop()
All these methods should work smoothly on modern MacOS versions. If you run into issues, double-check that your file path is correct and that you’ve installed the required libraries properly.
内容的提问来源于stack exchange,提问作者Johnson Tu

