-1

I have a class where I create a Label on the init method:

import tkinter as tk
from tkinter.filedialog import askopenfilename

class app(tk.Tk):
    def __init__(self, master):
        label1 = tk.Label(master, text="Select file...")
        label1.pack()

Then with a button I call a method to choose a file and change the label text to filename path.

    def files(self):
        filename = askopenfilename()
        self.label1.config(text=filename)

The problem is that when I choose the file, the app gets closed without errors, so I don't know what's going on.

Outside the class I have:

root = tk.Tk()
app_gui = app(root)
root.mainloop()
Nanush7
  • 23
  • 4
  • You need to set `self.label1` in `__init__` method. Right now it's a local name `label1`, not an instance attribute `self.label1`. – r.ook Jan 27 '20 at 15:52
  • Read up on [Python Classes and Objects, Section "The self"](https://www.geeksforgeeks.org/python-classes-and-objects/) and [Why are multiple instances of Tk discouraged?](https://stackoverflow.com/questions/48045401/why-are-multiple-instances-of-tk-discouraged) – stovfl Jan 27 '20 at 16:20
  • @stovfl Ok, thank you. – Nanush7 Jan 27 '20 at 16:46

1 Answers1

0

In your specific case, there are two problems. The first is that you're creating two instances of tk.Tk. You should never do that.

The second is that you aren't creating self.label1 so any attempt to modify it will fail.

The solution is to first remove tk.Tk as a superclass for app. The second is to properly define self.label1

class app():
    def __init__(self, master):
        self.label1 = tk.Label(...)
        ...

On a side note, you should seriously consider following the naming conventions of PEP8 and name your main class App. PEP8 is nearly universal in the python world, and deviating from it makes your code harder to read.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685