我试图使用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()
答案 0 :(得分: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()
答案 1 :(得分:1)
我能想到的最简单的方法是制作StringVar
file_var = Tkinter.StringVar(main_window, name='file_var')
使用lambda
更改您的回叫命令,将StringVar
传递给您的回调
command = lambda: open_file_handler(file_var)
然后在你的回调中,将StringVar
设置为file
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()