[英]How to make variable of a function global within a class?
因此,在理解如何从类中的另一个函数访问函数的变量值时遇到了一些麻烦。
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")])
现在,文件名只是loadfile
函数中的局部变量。 您需要将filename设置为对象的属性。 执行self.filename = ...
,然后在其他方法中可以将其作为self.filename
进行访问。
(在这种情况下,您要问的内容似乎有些奇怪,因为在您似乎想访问filename
的时候不会调用loadfile
,因此filename
甚至都不存在。但这是一般性的想法。无论如何,您显然必须先调用定义了变量的函数,然后才能对其进行任何操作。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.