python-3.x - 有什么办法可以将浏览文件按钮更改为它的文件路径?
问题描述
我正在制作一个需要浏览照片的程序,并且我已经放置了浏览文件按钮并且一切正常,但是我希望当用户选择一个文件时将按钮名称更改为该文件的路径,请帮助。
我尝试在函数内部使用全局,因此我可以在函数“浏览文件”中命名一个变量,并在函数内部更改它的名称并将其插入到按钮中,但它对我不起作用,也许我没有不知道如何或它不这样工作
from tkinter import *
from tkinter import filedialog
window = Tk()
window.geometry('500x500')
def filename1():
window.filename1 = filedialog.askopenfilename(initialdir="/",title="Select file", filetypes=(
('jpeg', "*.jpeg"), ("jpg", "*.jpg"), ("all files", "*.*")))
print(window.filename1) # here it's print the file path
filebrowsebutton1 = Button(text="Browse a file",command=filename1).place(x=60, y=280)
window.mainloop()
解决方案
首先返回文件名 fromfilename1()
不会更改浏览按钮的文本。第二个filebrowsebutton1
不会分配实例引用Button
,而是None
因为你已经链接了函数.place(...)
。
以下是解决上述问题的代码更新版本:
import tkinter as tk
from tkinter import filedialog
window = tk.Tk()
window.geometry('500x500')
def filename1():
filename = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('jpeg', '*.jpeg *.jpg'),('all files', '*.*')))
if filename:
# update button text with the selected filename
browsebutton['text'] = filename
browsebutton = tk.Button(text='Browse a file', command=filename1)
browsebutton.place(x=60, y=200)
window.mainloop()
推荐阅读
- c - 如何将结构从函数返回到结构指针?
- lua - 无法上传到 NodeMCU Lua
- c# - 会话在 60 秒后超时
- java - 由于空对象,Java IBM Lotus Notes 从视图中检索数据在中间失败
- android - Chromecast v3| 安卓 | 如何使用自定义命名空间?
- c# - Linux平台.NET Core中线程的ApartmentState是什么意思?
- django - 我正在使用 django 自定义后端检查 JWTtoken 有错误:用户配置文件匹配查询不存在?
- sql - 无效的标识符 SQL ORA-00904
- c++ - C ++打印降序然后升序的零点递归模式
- python - 在for循环中加入数据框