倚天杖
# -*- coding:utf8 -*-from Tkinter import *from tkFileDialog importaskopenfilenameroot = Tk()root.title()root.geometry()def open_file():file_path = askopenfilename(filetypes=(("files", "*.txt"),("All files", "*.*")))t.insert(END, file_path +'\n')print file_pathprint file_patht = Text()t.pack()Button(root, text="Open File",command=open_file).pack()root.mainloop()按你的思路来啊,首先说为什么会报错。。你发现你定义了一个open_file函数之后就直接print file_path了嘛,可是这个时候file_path还没定义诶。。然后你这个file_path是一个局部变量,想要在函数外部使用必须global。。# -*- coding:utf8 -*-from Tkinter import *from tkFileDialog import askopenfilenameroot = Tk()root.title()root.geometry()file_path = askopenfilename(filetypes=(("files", "*.txt"),("All files", "*.*")))def open_file():global file_patht.insert(END, file_path +'\n')print file_pathprint file_patht = Text()t.pack()Button(root, text="Open File",command=open_file).pack()root.mainloop()所以代码就成了这样