【问题标题】:How to open and select a file in Python如何在 Python 中打开和选择文件
【发布时间】:2021-08-19 15:07:42
【问题描述】:

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

【问题讨论】:

  • 您可以发布您尝试过的代码的最小版本吗?该代码在哪里冻结?
  • 调试您的代码,使其不会冻结
  • @SuperStew 听起来很像:“解决你的问题,这样你就没有它了”,如果 OP 提供了minimal reproducible example,那就太好了

标签: python dialog


【解决方案1】:

如 cmets 中所述,您应该提供一个最小的可重现示例。既然你是新成员,我给你这个例子,可以在这里找到。 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()

【讨论】:

  • 好的,我设法用函数解决了它!谢谢!!
猜你喜欢
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多