【问题标题】:Calling a variable from one function in another在另一个函数中调用一个变量
【发布时间】:2016-02-27 15:10:36
【问题描述】:

我有一个类,其中存在两个函数。

我希望从另一个函数访问在一个函数中创建的变量。

这是我正在尝试做的一个示例:

def __init__(self, parent, controller):
    tk.Frame.__init__(self,parent)

    Message1 = None
    Keyword1 = None
    Keyword2 = None


    Message_Ent = tk.Entry(self, textvariable = Message1)
    Key1_Ent = tk.Entry(self, textvariable = Keyword1)
    Key2_Ent = tk.Entry(self, textvariable = Keyword2)


def Main_Cipher(*args):
    #Need to use these variables:
    #Message1
    #Keyword1
    #Keyword2

【问题讨论】:

  • 在课堂上使用self.variable
  • 你能举个例子吗?我不太清楚你在问什么。
  • Tkinter 与 python 中的其他任何东西没有什么不同。没有看到代码就不可能知道你做错了什么。请阅读stackoverflow.com/help/mcve

标签: python function


【解决方案1】:

现在Message1Keyword1Keyword2local variables。你想让他们成为班级的instance variables。您可以使用 self 关键字来执行此操作:

def __init__(self, parent, controller):
    tk.Frame.__init__(self,parent)

    self.Message1 = None
    self.Keyword1 = None
    self.Keyword2 = None


    Message_Ent = tk.Entry(self, textvariable = self.Message1)
    Key1_Ent = tk.Entry(self, textvariable = self.Keyword1)
    Key2_Ent = tk.Entry(self, textvariable = self.Keyword2)


def Main_Cipher(*args):
    #these are now accessible here:
    print self.Message1
    print self.Keyword1
    print self.Keyword2

【讨论】:

  • 那只是输出:变量的 PY_VAR0、PY_VAR1、PY_VAR2
  • 所以这些是这些变量的值......这不是你所期望的吗?看这里,你可能会覆盖它们:stackoverflow.com/questions/31126872/…
猜你喜欢
  • 2018-04-29
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多