gpt4 book ai didi

python - 如何在类范围之外访问变量定义的浏览按钮类

转载 作者:行者123 更新时间:2023-12-01 07:34:29 26 4
gpt4 key购买 nike

我从主函数中调用了一类浏览按钮(用于选择文件位置)。该类具有浏览功能来捕获存储路径的文件路径变量。现在我只想使用在此类外部的类函数中定义的文件路径,就像在类范围之外打印此变量

我已经尝试过将 loc 作为全局的,其他访问方法,但没有一个有效,我猜这是因为参数被传递给类。

'''Using Tkinter module'''

class Browse(tk.Frame,object):
# here __init__ ,_create_widgets,_display_widgets are defined then I have,

def browse(self):
""" Browses a .xlsx file or all files and then puts it on the entry.
"""

self.filepath.set(fd.askopenfilename(initialdir=self._initaldir,
filetypes=self._filetypes))
print(self.filepath.get()), self #Path of ATP choosen by user
loc = self.filepath.get() #want to excess this out of class

我想在类范围之外打印“loc”值(能够在内部打印)我怎样才能访问相同的内容。我猜这个问题是由于我的类(class)的争论引起的,尽管不确定。

最佳答案

就目前而言,locbrowse 函数中的局部变量,当 browse 函数返回时,它将不再存在。如果你写成:

        self.loc = self.filepath.get()

然后,如果您有一个名为 bBrowse 对象,则只需编写 b.loc 即可访问它。

如果即使没有可用的Browse对象也想访问该变量,则需要一个类变量。设置为:

        Browse.loc = self.filepath.get()

并使用Browse.loc进行访问。不过,类变量的问题与所有全局变量的问题相同 - 如果您有两个 Browse 对象怎么办?如果您尝试从多个线程访问类变量怎么办?

关于python - 如何在类范围之外访问变量定义的浏览按钮类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57053531/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com