简体   繁体   中英

Python 3 - Tcl/Tk how to get filename from filedialog and change label

I am trying to select a file and have the label show its name.

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()

You can use a StringVar and pass it to the textvariable option of the label, so that each time the value of the variable is changed, the text of the label is too:

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()

Remark: grid() returns None so in your code,
photo_label = Button(image=photo, command=onOpen).grid()
just assigned the value None to photo_label .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM