Home > Back-end >  Tkinter - label doesn't update
Tkinter - label doesn't update

Time:02-23

This morning I started to work on a little app so I can understand better TkInter. I didn't get too far because I can't make the label to update after I press a button.

It seems like after I create an instance of the Label object I can't work on it anymore because of the mainloop() I guess? I tried to use .update() and other ways to make this work but I can't figure it out. If I add () to file_explorer method, the label updates but I can't open the file explorer anymore and it also starts the file explorer without pressing the button so it's pointless. Found something here on StackOverflow but still nothing.

from tkinter import *
from tkinter import filedialog as fd
import os

# Main_window
App = Tk()
App.geometry("300x300")
App.resizable(0, 0)

filename = "empty"


class Btn:
    def __init__(self, master, pos_x, pos_y, label):
        frame = Frame(master)
        frame.pack()

        self.Button = Button(master, text=label, command=self.file_explorer)
        self.Button.place(x=pos_x, y=pos_y)

    def file_explorer(self):
        global filename
        filename = fd.askopenfilename(filetypes=(('text files', '*.txt'), ('All files', '*.*')))
        filename = os.path.basename(filename)


class FileLabel:
    def __init__(self, master, pos_x, pos_y):
        global filename
        frame = Frame(master)
        frame.pack()

        self.label1 = Label(master, text=filename)
        self.label1.place(x=pos_x, y=pos_y)


e = Btn(App, 10, 10, "Browse file")
f = FileLabel(App, 90, 12)

App.mainloop()

CodePudding user response:

Updating filename will not update the label automatically. However, you can use StringVar instead of normal string and textvariable option of Label to achieve the goal:

...
filename = StringVar(value="empty")

class Btn:
    def __init__(self, master, pos_x, pos_y, label):
        frame = Frame(master)
        frame.pack()

        self.Button = Button(master, text=label, command=self.file_explorer)
        self.Button.place(x=pos_x, y=pos_y)

    def file_explorer(self):
        fname = fd.askopenfilename(filetypes=(('text files', '*.txt'), ('All files', '*.*')))
        # update filename
        filename.set(os.path.basename(fname))


class FileLabel:
    def __init__(self, master, pos_x, pos_y):
        frame = Frame(master)
        frame.pack()

        self.label1 = Label(master, textvariable=filename) # used textvariable instead
        self.label1.place(x=pos_x, y=pos_y)

...
  • Related