2013-10-31 16 views
0

我試圖用tkinter打開一個文件對話框,一旦打開這個文件對話框,我該如何獲取函數返回的文件對象。至於在我如何訪問它在主?訪問文件名的python文件對話框

基本上我如何通過由命令調用返回file變量

import sys 
import Tkinter 
from tkFileDialog import askopenfilename 
#import tkMessageBox 

def quit_handler(): 
    print "program is quitting!" 
    sys.exit(0) 

def open_file_handler(): 
    file= askopenfilename() 
    print file 
    return file 


main_window = Tkinter.Tk() 


open_file = Tkinter.Button(main_window, command=open_file_handler, padx=100, text="OPEN FILE") 
open_file.pack() 


quit_button = Tkinter.Button(main_window, command=quit_handler, padx=100, text="QUIT") 
quit_button.pack() 


main_window.mainloop() 
+0

你不要的文件,或者......你設置一個全局變量...通常你會在open_file_handler方法中執行所有的處理,或者你從那個方法中調用的方法作爲爭論 –

回答

3

相反功能的返回值,只是處理一下那裏(我也改名爲file變量,這樣你就不會覆蓋內置-in類):

def open_file_handler(): 
    filePath= askopenfilename() # don't override the built-in file class 
    print filePath 
    # do whatever with the file here 

或者,你可以簡單地鏈接按鈕到另一個功能,處理它有:

def open_file_handler(): 
    filePath = askopenfilename() 
    print filePath 
    return filePath 

def handle_file(): 
    filePath = open_file_handler() 
    # handle the file 

然後,在按鈕:

open_file = Tkinter.Button(main_window, command=handle_file, padx=100, text="OPEN FILE") 
open_file.pack() 
1

我能想到的最簡單方法是使用lambdaStringVar傳遞給你的回調做出StringVar

file_var = Tkinter.StringVar(main_window, name='file_var') 

改變你的回調命令

command = lambda: open_file_handler(file_var) 

然後在您的通話中背部,設置StringVarfile

def open_file_handler(file_var): 
    file_name = askopenfilename() 
    print file_name 
    #return file_name 
    file_var.set(file_name) 

然後在你的按鈕使用command,而不是open_file_handler

open_file = Tkinter.Button(main_window, command=command, 
          padx=100, text="OPEN FILE") 
open_file.pack() 

然後你可以檢索使用

file_name = file_var.get()