Python3-Tcl/Tk如何从filedialog获取文件名并更改标签

Python3-Tcl/Tk如何从filedialog获取文件名并更改标签,python,tkinter,tk,Python,Tkinter,Tk,我正在尝试选择一个文件,并让标签显示其名称 def onOpen(): photo_label = filedialog.askopenfilename() pass #photo code photo = PhotoImage(file="smile.png") photo_label = Button(image=photo, command=onOpen).grid() #I am attempting to change text=photo_label to ref

我正在尝试选择一个文件,并让标签显示其名称

def onOpen():
    photo_label = filedialog.askopenfilename()
    pass


#photo code
photo = PhotoImage(file="smile.png")
photo_label = Button(image=photo, command=onOpen).grid()
#I am attempting to change text=photo_label to reflect the file name
text = Label(text=photo_label) # included to show background color
text.grid()

您可以使用
StringVar
并将其传递给标签的
textvariable
选项,以便每次更改变量的值时,标签的文本也是:

import tkinter as tk
from tkinter import filedialog

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

root = tk.Tk()
# StringVar that will contain the file name
photo_label = tk.StringVar(root)

photo = tk.PhotoImage(file="smile.png")
tk.Button(root, image=photo, command=onOpen).grid()

text = tk.Label(root, textvariable=photo_label)
text.grid()

root.mainloop()
备注:
grid()
返回
None
因此在您的代码中,
photo\u label=按钮(image=photo,command=onOpen).grid()

刚刚将值
None
分配给
photo\u标签