![](/img/trans.png)
[英]Python 3 - Tcl/Tk how to get image from filedialog and display it?
[英]Python 3 - Tcl/Tk how to get filename from filedialog and change label
我正在嘗試選擇一個文件並使標簽顯示其名稱。
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_label = Button(image=photo, command=onOpen).grid()
剛剛將值None
分配給photo_label
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.