I am adding a "select file section" to my code. I would like to have two options, first choosing file path and second entering the file path.
Another feature I couldn't implement is that if the user choose the file path, that path appears in the entry section.
This is the section of the code that I am talking about:
from tkinter import filedialog
import tkinter as tk
class open_file:
def __init__(self, master):
self.master = master
self.file_path = ''
self.b1 = tk.Button(master,
text = 'Open',
command = self.open_file).grid(row=0, column=1)
v = tk.StringVar(root, value = self.file_path)
self.l1 = tk.Entry(master, width=24, textvariable=v).grid(row=0, column=0)
def open_file(self):
self.file_path = filedialog.askopenfilename(filetypes = (("Python Files", "*.py")
,("All files", "*.*") ))
root = tk.Tk()
app = open_file(root)
root.mainloop()
Since you have a StringVar linked to the text, you'll need to use StringVar.set()
in order to set the text of the entry.
From http://effbot.org/tkinterbook/variable.htm:
The set method updates the variable, and notifies all variable observers. You can either pass in a value of the right type, or a string.
You've set the contents on the StringVar, but they won't update dynamically whenever self.file_path changes. In your case you'll have to make the StringVar (v) a class member in the __init__ function
self.v = tk.StringVar(root, value = self.file_path)
Additionally, when you want to update the file path set it via self.v.set(String)
def open_file(self):
self.file_path = filedialog.askopenfilename(filetypes = (("Python Files", "*.py")
,("All files", "*.*") ))
if self.file_path: #check if file path is not None or empty
self.v.set(self.file_path)