Rafael Franco
Rafael Franco

Reputation: 29

Using a variable from one function onto another

I got a problem using variables from one function onto another.

This is my code:

import tkinter as tk

def form ():
    textVar = tk.StringVar()
    entry0 = tk.Entry(self, textvariable = textVar).pack()

def toPrint():
    texto = textVar.get()
    print(texto)

def button():
    button0 = tk.Button(text="Summit", command = toPrint).pack()

Now the variable being called in toPrint() is local from form(), therefore I can not use it without using global, but that is causing issues with the rest of my code since I'm using form() more than once, is there any other way to solve it?

I would appreciate if the explanation is simple, I'm still a beginner.

I already have searched for this in SO, but I did not manage to understand the answers.

Upvotes: 1

Views: 47

Answers (1)

Leona.li
Leona.li

Reputation: 486

I am a foreigner to English, so firlstly I apologized for my impolite or wrong use of English word. Just want to say I really do not mean it.

And for this question, maybe you could try to put these in the same class. And try to make the variables you want to called several times the attribute of the class.

For example:

class myclass():
    def __init__ (self):
        self.textVar = tk.StringVar()
        self.entry0 = tk.Entry(self, textvariable = textVar).pack()

    def toPrint(self):
        texto = self.textVar.get()
        print(texto)

Upvotes: 2

Related Questions