![](/img/trans.png)
[英]How to get the route of selected file using filedialog.askopenfilename() from another method in TkInter Python 3
[英]Get a file's directory in a string selected by askopenfilename
我正在編寫一個程序,您使用askopenname文件對話框選擇一個文件,然后將其保存到字符串中,以便可以使用另一個函數(已經完成)將文件提取到另一個位置,是預定的。 我打開文件對話框的按鈕代碼是這樣的:
`a = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))`
這應該是您想要的:
import tkinter
import tkinter.filedialog
import getpass
# Need this for the `os.path.split` function
import os
gui = tkinter.Tk()
user = getpass.getuser()
def click():
# Get the file
file = tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user)
# Split the filepath to get the directory
directory = os.path.split(file)[0]
print(directory)
button = tkinter.Button(gui, command=click)
button.grid()
gui.mainloop()
如果您知道文件的實際位置,則始終可以使用以下方法來查詢目錄而不是文件:
from tkFileDialog import askdirectory
directory= askdirectory()
然后在代碼中:
import tkinter
import tkinter.filedialog
import getpass
from tkFileDialog import askdirectory
# Need this for the `os.path.split` function
import os
gui = tkinter.Tk()
user = getpass.getuser()
def click():
directory= askdirectory()
print (directory)
button = tkinter.Button(gui, command=click)
button.grid()
gui.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.