如何打开 select Python 中的文件

How to open and select a file in Python

我想通过在对话框中选择图像来打开 Python 中的图像,我该怎么做?我尝试了 tkinter 和 easygui,但是当我使用它们时,程序冻结并且从不加载。有什么建议吗?

如评论中所述,您应该提供一个最小的可重现示例。由于你是新成员,我给你这个例子,可以在这里找到。 https://www.geeksforgeeks.org/loading-images-in-tkinter-using-pil/

from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog


def open_img():
    # Select the Imagename  from a folder
    x = openfilename()

    # opens the image
    img = Image.open(x)

    # resize the image and apply a high-quality down sampling filter
    img = img.resize((250, 250), Image.ANTIALIAS)

    # PhotoImage class is used to add image to widgets, icons etc
    img = ImageTk.PhotoImage(img)

    # create a label
    panel = Label(root, image=img)

    # set the image as img
    panel.image = img
    panel.grid(row=2)


def openfilename():
    # open file dialog box to select image
    # The dialogue box has a title "Open"
    filename = filedialog.askopenfilename(title='"pen')
    return filename


# Create a window
root = Tk()

# Set Title as Image Loader
root.title("Image Loader")

# Set the resolution of window
root.geometry("550x300+300+150")

# Allow Window to be resizable
root.resizable(width=True, height=True)

# Create a button and place it into the window using grid layout
btn = Button(root, text='open image', command=open_img).grid(row=1, columnspan=4)
root.mainloop()