Fun*_*guy 6 python csv file-io tkinter python-2.7
我正在尝试使用浏览窗口创建GUI以查找特定文件.我之前发现了这个问题:在Python中浏览文件或目录Dialog
虽然当我查看条款时,它似乎并不是我想要的.
我需要的只是可以从Tkinter按钮启动的东西,它从浏览器返回所选文件的路径.
有人有资源吗?
编辑:好的,所以问题已得到解答.对于任何有类似问题的人,做你的研究,那里的代码都可以.不要在cygwin中测试它.由于某种原因它在那里不起作用.
Rob*_*rto 10
我认为TkFileDialog可能对你有用.
import Tkinter
import tkFileDialog
import os
root = Tkinter.Tk()
root.withdraw() #use to hide tkinter window
currdir = os.getcwd()
tempdir = tkFileDialog.askdirectory(parent=root, initialdir=currdir, title='Please select a directory')
if len(tempdir) > 0:
print "You chose %s" % tempdir
Run Code Online (Sandbox Code Playgroud)
编辑:这个链接有更多的例子
小智 10
我重新编写了Roberto 的代码,但用Python3重写了(只是做了一些小改动)。
您可以按原样复制并粘贴一个简单的演示 .py 文件,或者仅复制函数“ search_for_file_path ”(以及关联的导入)并作为函数放入您的程序中。
import tkinter
from tkinter import filedialog
import os
root = tkinter.Tk()
root.withdraw() #use to hide tkinter window
def search_for_file_path ():
currdir = os.getcwd()
tempdir = filedialog.askdirectory(parent=root, initialdir=currdir, title='Please select a directory')
if len(tempdir) > 0:
print ("You chose: %s" % tempdir)
return tempdir
file_path_variable = search_for_file_path()
print ("\nfile_path_variable = ", file_path_variable)
Run Code Online (Sandbox Code Playgroud)
在 python 3 中,它已重命名为 filedialog。您可以通过askdirectory方法(事件)访问文件夹,如下所示。如果您想选择文件路径,请使用askopenfilename
import tkinter
from tkinter import messagebox
from tkinter import filedialog
main_win = tkinter.Tk()
main_win.geometry("1000x500")
main_win.sourceFolder = ''
main_win.sourceFile = ''
def chooseDir():
main_win.sourceFolder = filedialog.askdirectory(parent=main_win, initialdir= "/", title='Please select a directory')
b_chooseDir = tkinter.Button(main_win, text = "Chose Folder", width = 20, height = 3, command = chooseDir)
b_chooseDir.place(x = 50,y = 50)
b_chooseDir.width = 100
def chooseFile():
main_win.sourceFile = filedialog.askopenfilename(parent=main_win, initialdir= "/", title='Please select a directory')
b_chooseFile = tkinter.Button(main_win, text = "Chose File", width = 20, height = 3, command = chooseFile)
b_chooseFile.place(x = 250,y = 50)
b_chooseFile.width = 100
main_win.mainloop()
print(main_win.sourceFolder)
print(main_win.sourceFile )
Run Code Online (Sandbox Code Playgroud)
注意:即使关闭 main_win 后变量的值仍然存在。但是,您需要使用该变量作为 main_win 的属性,即
main_win.sourceFolder
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49437 次 |
| 最近记录: |