[英]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.