【问题标题】:Retrieve a variable from another class从另一个类中检索变量
【发布时间】:2018-04-23 03:13:52
【问题描述】:

我有两个类,如何将 pathentry 变量传递给下一个类?本质上,pathentry 变量是在文本条目中输入的文件的路径名。

class LabelBrowseButtonWidget(AbsLabelInputWidget):
        """Class created to create button widgets in the header of the gui"""

    def create_input(self):
        filepath_var = StringVar()
        self.Button = ttk.Button(self,
                                 text="Select Input File",
                                 command=lambda: filepath_var.set(self.getFilePath())
                                 )
        self.Button.pack(fil=tk.X, padx=0, expand=True)

        pathentry = ttk.Entry(self, textvariable=filepath_var)
        pathentry.pack(fill=tk.X, padx=5, expand=False)

        return pathentry

    def getFilePath(self):
        filepath = filedialog.askopenfilename(filetypes=(("Excel Files", "*.xls"),
                                                         ("Excel Files", "*.xlsx")))
        return filepath

class LabelButtonWidget(AbsLabelInputWidget):
    """Button created for executing the import of the input file"""

    def create_input(self, *args):
        self.Button = ttk.Button(self,
                                 text="Import Input File",
                                 command=lambda: self.fileImport()
                                 )
        self.Button.pack(fil=tk.X, padx=5, expand=True)

    def fileImport(self):
        pathentry = LabelBrowseButtonWidget.create_input(self.pathentry.get())
        print(pathentry)
        # print("now what?")

我觉得我有点迷路了。

【问题讨论】:

  • 问题出在哪里?在def fileImportLabelButtonWidget?
  • 我需要将LabelbrowseButtonwidget类中path entry widget中的文本传递给Label Button widget中的fileImport。这很容易做到吗?我怎么能知道问题出在哪里来回答你的问题?抱歉,还是个初学者。

标签: python-3.x arguments parameter-passing


【解决方案1】:

我不太明白。

您想要一个可以从任何地方访问的变量吗?如果是这样,请使用global。定义变量时,先放这一行:

全局变量 然后在您访问它之前。

您想在创建类的实例时将变量传递给类吗?如果是这样,请使用__init__ 函数:

class classname(object):
    def __init__(self, variable):
        self.variable=variable

那么当你创建实例时:

instance=classname(variable)

并从类中访问变量:

self.variable

从外面看:

instance.variable

或者您只是想检索一个属于不同类的属性的变量?如果是这样:

instance.variable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2011-07-13
    • 2017-02-14
    • 2023-04-07
    相关资源
    最近更新 更多