Python 3 - Tcl/Tk 如何从文件对话框获取文件名并更改标签
Python 3 - Tcl/Tk how to get filename from filedialog and change label
我正在尝试 select 一个文件并让标签显示其名称。
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
,传给label的textvariable
选项,这样每次改变变量的值,label的文字也是:
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()
returns None
所以在你的代码中,
photo_label = Button(image=photo, command=onOpen).grid()
刚刚将值 None
分配给 photo_label
。
我正在尝试 select 一个文件并让标签显示其名称。
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
,传给label的textvariable
选项,这样每次改变变量的值,label的文字也是:
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()
returns None
所以在你的代码中,
photo_label = Button(image=photo, command=onOpen).grid()
刚刚将值 None
分配给 photo_label
。