Toni Barsties
Toni Barsties

Reputation: 11

Keep a variable in tkinter

So I have a code like this:

def awnser():
    a = 1
    print(a)
    return (a)

def opzP():
    opz = "+"
    print(opz)
    print(a)
    return

I want to click at the first button and the command "awnser" run. But later I want to click on another button and the command "opzP" should run. But it doesnt store the variable a. How can I store that. Thank you for your help ^^

The Return command and so on...

def awnser():
    a = 1
    print(a)
    return (a)

def opzP():
    opz = "+"
    print(opz)
    print(a)
    return

Error-Message instead of the variable.

Upvotes: 1

Views: 108

Answers (1)

rizerphe
rizerphe

Reputation: 1390

Witout using OOP, the easiest way to do so is to create a global variable:

a = 0
def do1():
    global a
    a=1
def do2():
    global a
    print(a)

But that's the bad way. Because it uses a global variable. The better way is:

class Funs:
    def __init__(self):
        self.a = 0
    def answer(self):
        self.a = 1
        print(self.a)
        return (self.a)
    def opzP(self):
        self.opz = "+"
        print(self.opz)
        print(self.a)
        return
obj = Funs()
Button(command=obj.answer).pack()
Button(command=obj.opzP).pack()

Hope that's helpful!

Upvotes: 1

Related Questions