0

I am trying to create a label that updates every time a file is selected from a filedialog. I followed the example here but I somehow started created multiple windows. What am I doing wrong?

import tkinter as tk
import tkinter.filedialog as fd

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.select_history = tk.Button(self,text="Select  Student History File",command=self.select_history).pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",command=root.destroy).pack(side="top")

        tk.Label(root, textvariable=historyfile).pack(side="bottom")        


    def select_history(self):
        fname = fd.askopenfilename()
        historyfile.set(fname)
        print(fname)

root = tk.Tk()
root.geometry("400x450+0+0")
root.configure(background="lightblue")

app = Application(master=root)
app.mainloop()
Rilcon42
  • 9,584
  • 18
  • 83
  • 167

1 Answers1

0

Your variable historyfile is undefined. Change tk.Label(root, textvariable=historyfile).pack(side="bottom") to

self.historyfile = tk.StringVar()
tk.Label(root, textvariable=self.historyfile).pack(side="bottom")

In the function select_history, use

self.historyfile.set(fname)

Total code:

import tkinter as tk
import tkinter.filedialog as fd

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.select_history = tk.Button(self,text="Select  Student History File",command=self.select_history).pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",command=root.destroy).pack(side="top")
        self.historyfile = tk.StringVar()
        tk.Label(root, textvariable=self.historyfile).pack(side="bottom")        


    def select_history(self):
        fname = fd.askopenfilename()
        self.historyfile.set(fname)
        print(fname)

root = tk.Tk()
root.geometry("400x450+0+0")
root.configure(background="lightblue")

app = Application(master=root)
app.mainloop()
ViG
  • 1,848
  • 1
  • 11
  • 13