monto
monto

Reputation: 61

Using variable from _init_

This is a section from my code. Basically, I want access to the value given in the entry box, which is a part of the def init ..Is there any way around this without using global variables? Also, it is set up this way so that this variable can be used throughout my program. Thanks.

import tkinter as tk

class MainApp(tk.Tk):

def test():
    a = __init__.test_entry.get()
    print(a)

def __init__(self, *args, **kwargs):
    tk.Tk.__init__(self, *args, **kwargs)

    test_entry = tk.Entry(self)
    test_entry.pack()

    submit_button = tk.Button(self, text="Submit", command=MyApp.test)
    submit_button.pack()

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

Upvotes: 1

Views: 940

Answers (2)

Blckknght
Blckknght

Reputation: 104762

No, there's no way for an external function to access the local variables defined in a function.

There are several ways to solve the problem you have without that though. You could make the variables defined in __init__ instance variables (attributes of self) and make sure your external function can access the right instance (perhaps in a global variable).

Or you could define a function within the __init__ function. Such a closure can access the variables defined in an outer namespace without issue. In your specific instance, you could even make the closure a really small one, using lambda to call the "real" outer function with an argument:

class MainApp(tk.Tk):
    def test(test_entry):
        a = test_entry.get()
        print(a)

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        test_entry = tk.Entry(self)
        test_entry.pack()

        submit_button = tk.Button(self, text="Submit", command=lambda: MyApp.test(test_entry))
        submit_button.pack()

The expression lambda: MyApp.test(test_entry) defines an unnamed function that keeps hold of the test_entry defined in the namespace of the __init__ method. When the lambda function is called, it passes that value on to the test function. You could also move the whole test definition into the __init__ method, and so call it directly, without a lambda, but that is often ugly as it involves lots of deep indentation.

Upvotes: 2

David Peters
David Peters

Reputation: 90

I'm not sure if i understand you correctly tbh

Have you considered using this instead?
self.__test_entry = tk.Entry(self)

Upvotes: 0

Related Questions