python - 如何使函数的变量在类中全局?

标签 python function tkinter global-variables

因此,我在理解如何从类中的另一个函数访问函数变量的值时遇到了一些麻烦。

    import Tkinter as tk, tkFileDialog

    class test:
        def __init__(self):
            root = tk.Tk()
            song_button = tk.Button(root, text = 'Select Song', fg = 'blue', command = self.loadfile).pack()
            #how do I access the value of filename now?

        def loadfile(self):
            filename = tkFileDialog.askopenfilename(filetypes=[("allfiles","*"),("pythonfiles","*.py")])

最佳答案

现在 filename 只是 loadfile 函数中的一个局部变量。您需要使文件名成为对象的属性。执行 self.filename = ...,然后在其他方法中您可以将其作为 self.filename 访问。

(在这种特殊情况下,您所要求的似乎有点奇怪,因为在您似乎想要访问filename时,不会调用loadfile ,所以 filename 甚至不存在。但这是一般的想法。无论如何,显然您需要调用定义变量的函数,然后才能对其执行任何操作。)

关于python - 如何使函数的变量在类中全局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12253195/

相关文章:

python - 设置函数以在python中调用raw_input

r - 在 R 中绘制 Haar 函数

python - TKInter Python 检查按钮状态

python - 如何在受用户限制的资源访问保护的 python eve api 中创建新的用户帐户

python - main.py 中的第 4 行未定义名称 'turtle'

c++ - C++ 中的 << 运算符是什么?

python - tkinter - 为什么会有像 bbox 这样的东西?

python - 在 ssh 中导入 pyplot 时,TypeError 构造函数返回 NULL

python - 将 int 数组转换为 chars 数组 - Python

python - 类型错误 : unsupported operand type(s)s for +: 'StringVar' and 'str' //Create a text file