python tkinter update content of a label when a file is opened

Viewed 1072

I'm currently programming a GUI using tkinter and Python 3. My problem here is i made a Label with which i want to display the path of a file i opened via the askopenfilename() method and this path is not "generated" when i start the program, obviously, so the Label is empty which makes sense but i don't know how to fix it. I'm gonna put the needed code below (I'm going to cut unnecessary code for this question):

import tkinter as tk

class Graphicaluserinterface(tk.Frame):

    def __init__(self,master=None):
        super().__init__(master)
        self.grid()
        self.fileopenname=tk.StringVar()
        self.menubar = tk.Menu(self)
        self.create_widgets()

    def create_widgets(self):
        self.inputpathdisplay = tk.Label(self,textvariable=self.fileopenname,bg="white",width=30)
        self.inputpathdisplay.grid(row=1,column=8,columnspan=3,sticky = "W")
    def fileopening(self):
        from tkinter.filedialog import askopenfilename
        self.fileopenname = askopenfilename(filetypes = [("binary files","*.bin*"),("all files","*.*")])


root = tk.Tk()
app = Graphicaluserinterface(master=root)
root.config(menu=app.menubar)
app.mainloop()

I read about using update_idletasks(). If this is correct in my case how would i go about implementing it here?

1 Answers

Right now you are doing self.fileopenname = askopenfilename() and this will redefine self.fileopenname as a string instead of a StringVar(). To correct this you need to set the value of StringVar with set().

That said you should also define all your imports at the top of your code instead of in your function.

import tkinter as tk
from tkinter.filedialog import askopenfilename


class Graphicaluserinterface(tk.Frame):

    def __init__(self,master=None):
        super().__init__(master)
        self.grid()
        self.fileopenname=tk.StringVar()
        self.menubar = tk.Menu(self)

        self.inputpathdisplay = tk.Label(self, textvariable=self.fileopenname, bg="white")
        self.inputpathdisplay.grid(row=1,column=8,columnspan=3,sticky = "W")
        self.fileopening()

    def fileopening(self):
        self.fileopenname.set(askopenfilename(filetypes = [("binary files","*.bin*"),("all files","*.*")]))


root = tk.Tk()
app = Graphicaluserinterface(master=root)
root.config(menu=app.menubar)
app.mainloop()
Related