Home > OS >  button change its text to the file name
button change its text to the file name

Time:09-22

How do I force the button to change its text to the filename? Everything works fine, a dialog box opens and files open too. But I still can't change the button name to the file name and save it.

Here is the code:

import tkinter.filedialog as tfd
import tkinter as tk
import os


window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""

def open():
    global file_name
    file_name = tfd.askopenfilename()
    os.startfile(file_name) #open file


btn1 =  tk.Button(window, text=f"Open {file_name}", command=open) #button
btn1.place(x = 20, y = 25)

CodePudding user response:

You can set the buttons text property using.

button['text'] = fileName

You can also read the button text propeerty to make sure it has been set to the file name in code, I.e. with an if statement.

bText = button['text']

CodePudding user response:

Try using .config -

import tkinter.filedialog as tfd
import tkinter as tk
import os


window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""

def open():
    global file_name
    file_name = tfd.askopenfilename()
    btn1.config(text=file_name) # Configure the button's text
    os.startfile(file_name) #open file


btn1 =  tk.Button(window, text=f"Open {file_name}", command=open) #button
btn1.place(x = 20, y = 25)

But if you run this code, the button name gets changed to the complete pathname (e.g. - C:/.../Choosen.file), so if you want only the file name ('Choosen.file') then use this -

btn1.config(text=file_name.split('/')[-1])

CodePudding user response:

You can use:

window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""


def open():
    global file_name
    file_name = tfd.askopenfilename()
    btn1["text"]  = " '"   file_name   "'"
    os.startfile(file_name)


btn1 = tk.Button(window, text="Open file", command=open)  # button
btn1.place(x=20, y=25)

tk.mainloop()

This uses the old text of the button and appends '{file_path}' to it -> Open file '{file_path}'

CodePudding user response:

You could define a new class that maintains state. This way you can avoid the global, and will be able to make multiple buttons each with their own files.

class FileButton(tk.Button):
    def __init__(self, window, file_name=""):
        super().__init__(window, command=self.open)
        self.set_text(file_name)

    def set_text(self, file_name):
        self.file_name = file_name
        self["text"] = f"Open {self.file_name}"

    def open(self):
        if self.file_name == "":
            self.set_text(tfd.askopenfilename())
        os.startfile(self.file_name)
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)

btn1 = FileButton(window)
btn1.place(x=20, y=25)

window.mainloop()
  • Related