【问题标题】:Accessing the variable inside nested function python访问嵌套函数python中的变量
【发布时间】:2018-07-16 07:02:07
【问题描述】:

我正在尝试访问在类内部以及嵌套函数内部的变量。我正在尝试将该变量访问到另一个类中,但是在使用 'global' 之后我没有运气访问它。谁能帮忙 这是代码

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        #Some code


    def show_frame(self, page_name):
        #Some code

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        #Some code


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

        def click():
            entered_text=textentry.get()
            #Some code

class PageTwo(StartPage,PageOne):

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

        #Some code

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

我正在尝试将存在于PageOne 类中的entered_text 访问到__init__ 方法中的PageTwo 类中

问候 萨加尔

【问题讨论】:

  • 你能做一个最小的、完整的、可验证的例子吗? stackoverflow.com/help/mcve
  • 例如用户 pass 而不是 #some code 并在没有不必要的 tk 参考的情况下制作最小示例。

标签: python global-variables local-variables class-variables nested-function


【解决方案1】:

首先,为什么在 init 方法中定义click()?

此外,只要 click() 不返回 entered_text 值(这样您就可以将其输出存储在另一个变量中,或者它不更新类属性(例如如果你有一个 self.entered_text 变量,那么它只存在于函数执行期间。

这就是我的意思:

示例 1:

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

    def click():
        entered_text = textentry.get()
        return entered_text

if __name__ == "__main__":
    my_instance = PageOne()
    my_instance.click()
    print(my_instane.entered_text)

示例 2:

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
         self.entered_text = str()

    def click():
        self.entered_text = textentry.get()

【讨论】:

  • 感谢这位 arkwright。我知道如何使用“self”,但是 click() 应该出现在 init 中,因为我已经在构造函数中进行了一些变量初始化
猜你喜欢
  • 2019-04-04
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 2015-08-13
  • 2022-06-23
  • 1970-01-01
  • 2022-01-25
  • 2019-11-21
相关资源
最近更新 更多