0

我试图使用 tkinter 打开文件对话框,一旦打开此文件对话框,我如何获取函数返回的文件对象。就像我如何在 main 中访问它一样?

基本上我如何通过命令调用的函数处理返回值

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()
4

2 回答 2

3

不要返回file变量,只需在那里处理它(我还重命名了file变量,因此您不会覆盖内置类):

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()
于 2013-10-31T17:46:06.537 回答
1

我能想到的最简单的方法是制作一个StringVar

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

更改您的回调命令,lambda以将其传递StringVar给您的回调

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()
于 2013-10-31T17:49:46.653 回答