Python 3 - Tcl/Tk 如何从文件对话框中获取图像并显示它?

Python 3 - Tcl/Tk how to get image from filedialog and display it?

我正在尝试 select 文件对话框中的文件并在 GUI 中显示图片

def onOpen():
    """ Ask the user to choose a file and change the update the value of photo"""
    photo= get(filedialog.askopenfilename())

photo2 = PhotoImage(filedialog=photo)
#how do I get photo2 to work and get button to display the picture?
button = Button(root, image=photo2, text="click here", command=onOpen).grid()

root.mainloop()

你想要达到的效果可以分三步完成:

  • 获取用户选择图片的路径
    filename = filedialog.askopenfilename()

  • 创建 PhotoImage

  • 使用 configure 方法更改按钮的图像

此外,您需要使包含 PhotoImage 的变量成为全局变量,这样它就不会被垃圾回收。

import tkinter as tk
from tkinter import filedialog

def onOpen():
    global photo
    filename = filedialog.askopenfilename()
    photo = tk.PhotoImage(file=filename)
    button.configure(image=photo)

root = tk.Tk()

photo = tk.PhotoImage(file="/path/to/initial/picture.png")
button = tk.Button(root, image=photo, command=onOpen)
button.grid()

root.mainloop()