How can I use .get() tkinter in another def? Python How can I use .get() tkinter in another def? Python tkinter tkinter

How can I use .get() tkinter in another def? Python


The problem is with Python's scopes I talked about them in another answer of mine.

As Kevin said, you can use global declarations:

global foo

This is discouraged, the best use of global is no global at all, so I won't explain how it works.


The other way to make that work is by using classes. In classes, def can use definitions from other functions, just what you want. Normally you can't use them between functions, for example, this will raise an error:

def foo1():    string = 'x'def foo2():    print(string)foo1() #You would expect this to define the stringfoo2() #So this can print it... but no.

But this will work:

class foo:    def foo1(self):        self.string = 'x'    def foo2(self):        print(self.string)MyClass = foo()MyClass.foo1()MyClass.foo2()

Line per line explanation:

First, this line:

MyClass = foo()

This is actually making what's called an instance of the class. This will allow that each variable, function, or other thing defined in a instance can be accessed, from:

  • Outside the same instance, or even outside of the class or any class, by using MyClass.var, MyClass.var(), etc.
  • From the instance, by using self.var, self.var(), etc.

Think of these in this way: A is an instance of a class, which has a method foo() and a method bar(). Somewhere in the code foo() calls bar(). If you want to call the foo() function from A in anywhere in the code use: A.foo(). If you had another instance, B then to call B's foo() you use B.foo() and so on. When foo() from any instance calls bar() from the same instance the line of code is self.bar(). So, self represents any instance of a class.

The other lines

  1. This is similar to defining a function, you are telling Python that the next indented lines belong to a class (instead of a function)
  2. Define a function with no parameters (self is obligatory in a class, there is a reason for this)
  3. string = 'x' for every instance of this class
  4. Same as 2.
  5. Show the corresponding (with the instance) string x in screen.

And then instantiates the class, and calls foo1() and foo2()


Now you can apply that knowledge to fixing your code. If something is unclear I'll edit my question.