首页 > 解决方案 > 有什么办法可以将浏览文件按钮更改为它的文件路径?

问题描述

我正在制作一个需要浏览照片的程序,并且我已经放置了浏览文件按钮并且一切正常,但是我希望当用户选择一个文件时将按钮名称更改为该文件的路径,请帮助。

我尝试在函数内部使用全局,因此我可以在函数“浏览文件”中命名一个变量,并在函数内部更改它的名称并将其插入到按钮中,但它对我不起作用,也许我没有不知道如何或它不这样工作

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

标签: python-3.xselenium-webdrivertkinter

解决方案


首先返回文件名 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()

推荐阅读