简体   繁体   English

从一个函数到另一个函数使用变量

[英]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? 现在在toPrint()中调用的变量是form()的局部变量,因此我不能在不使用global的情况下使用它,但这会导致其余代码出现问题,因为我多次使用form(),还有其他解决方法吗?

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. 我已经在SO中搜索过此内容,但我无法理解答案。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM