Tkinter filedialog askopenfilename 函数

Tkinter filedialog askopenfilename function

我试图在用户通过调用函数 open:[=15= 按下按钮时打开 file dialog(select 文件)window ]

from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
from PIL import ImageTk, Image

root = Tk()
root.title('Application')


def open_file():
    root.filename = tkFileDialog.askopenfilename(initialdir="/", title="Select An Image", filetypes=(("jpeg files", "*.jpg"), ("gif files", "*.gif*"), ("png files", "*.png")))
    image_label = Label(root, text=root.filename)
    image_label.pack()
    my_image = ImageTk.PhotoImage(Image.open(root.filename))
    my_image_label = Label(root, image=my_image)
    my_image_label.pack()

my_button = Button(root, text="Open File", command=open_file)
my_button.pack()
root.mainloop()

然而,在我 select 选择的文件和 'submit' 它之后,它不会出现在我创建的 my_image_label 上(只有一个空白 space 大小图片的出现) 但是当我在函数之外使用 open 函数内容时(不调用函数)它起作用了。

您知道问题出在哪里吗?我该如何解决?

我没有安装 2.7,所以这是我最好的猜测: root.filename 我认为应该只是文件名。

print root.filenamereturn是什么意思?

编辑:我的第一个猜测是错误的。我已经修改它以在 3.6 中工作并且几乎没有改变任何东西:

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

root = Tk()
root.title('Application')


def open_file():
    filename = filedialog.askopenfilename(initialdir="/", title="Select An Image", filetypes=(("jpeg files", "*.jpg"), ("gif files", "*.gif*"), ("png files", "*.png")))
    image_label = Label(root, text=filename)
    image_label.pack()
    my_image = ImageTk.PhotoImage(Image.open(filename))
    my_image_label = Label(root, image=my_image)
    my_image_label.pack()

my_button = Button(root, text="Open File", command=open_file)
my_button.pack()
root.mainloop()

您可以使用更新版本的 python 吗?还是一定要学2.7?

编辑: 忘记我说的任何话。只需添加这一行: my_image_label.photo = my_image 包装标签之前。