0

I'm trying to have the user click on the "New Window" button to open a new window, and then click on the "Browse" button to choose a file. The file path should then be displayed in the Entry Box. My issue is that I can't get the file path to be displayed. Here's my code:

import tkinter as tk
from tkinter import filedialog

class NewWindow(tk.Toplevel):
    def __init__(self, parent):
        super().__init__(parent)
        self.title('New Window')
        self.file_var = tk.StringVar()
        txt_box = tk.Entry(self,
                        textvariable = self.file_var.get())
        txt_box.grid(column = 2, row = 1, padx = 10, pady = 10)
        btn = tk.Button(self,
                        text = 'Browse',
                        command=self.getFilePath)
        btn.grid(column = 1, row = 1, padx = 10, pady = 10)

    def getFilePath(self):
        file_path = filedialog.askopenfilename(initialdir = "/",
                                           title = "Select a file")
        self.file_var.set(file_path)
        
class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title('Main Window')
        btn = tk.Button(self,
                        text='New Window',
                        height = 3,
                        width = 12,
                        command=self.open_new_window)
        btn.grid(column = 1, row = 1, padx = 10, pady= 10)
        
    def open_new_window(self):
        window = NewWindow(self)
        window.grab_set()


if __name__ == "__main__":
    app = App()
    app.mainloop()

Thanks for the help!

Reactions
  • 3
  • 3
  • 1
    there is a method in entry which is `insert ` this method allow you to write whatever you want in the `entry ` . you could use it like : `txt_box.insert('end','put here what you want')` – Ayyoub ESSADEQ May 16 '22 at 21:56
  • The `textvariable=` option should be the `StringVar` (or similar Var type) itself, rather than the result of calling `.get()` on the Var. – jasonharper May 16 '22 at 22:00
  • I feel silly. changing the self.file.get() to self file on the text box fixed it. Thank you! – Reactions May 16 '22 at 22:41

1 Answers1

0

Remove that get() from textvariable=self.file._var.get()

It should be

txt_box = tk.Entry(self,textvariable = self.file_var)