我對python很陌生。我用 tkinter 開發了一個簡單的 GUI 來選擇檔案。當按下按鈕時,打開檔案對話框被激活,用戶可以從檔案夾中選擇檔案。這是我的代碼:
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
# %% create a command associated to the window button
def open_file():
initialDir = '/';
fileTypes = (('Text files', '*.txt'), ('Csv files', '*.csv'), ('All files', '*.*'));
Title = 'Choose a file';
filename = str(fd.askopenfile(title=Title, filetypes=fileTypes));
# %% create a GUI
window = tk.Tk();
window.title('Tkinter GUI Open File Dialog');
window.resizable(False, False);
window.geometry('300x150');
# %% open file button
open_button = ttk.Button(window, text='Open a File',command=open_file);
open_button.grid(column=0, row=1, sticky='w', padx=10, pady=10)
# %% run window - automatic closing after 10 seconds
window.after(10000,lambda:window.destroy())
window.mainloop();
我想獲取所選檔案的檔案名。此外,我想在按下按鈕并且檔案名已知時關閉 gui。謝謝你們!
uj5u.com熱心網友回復:
此時您將其分配給區域變數filename,但如果您添加 global filename內部函式,那么它將分配給全域變數。
在開始時為全域變數分配一些默認值可能會很好 - 因此即使您不選擇檔案它也會存在。
如果您只想要檔案名(而不是對打開的檔案的參考),則使用askopenfilename而不是askopenfile
如果您單擊Cancel然后askopenfilename應該給出None,最好保留它None而不是轉換為字串。稍后您應該檢查是否filename僅None在您確實選擇了檔案名時才運行代碼。
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
filename = None # default value in global variable
# %% create a command associated to the window button
def open_file():
global filename # inform function to use global variable instead of local one
initialDir = '/'
fileTypes = (('Text files', '*.txt'), ('Csv files', '*.csv'), ('All files', '*.*'))
Title = 'Choose a file'
# use askopenfilename instead of askopenfile to get only name
filename = fd.askopenfilename(title=Title, filetypes=fileTypes)
# destroy GUI
window.destroy()
# %% create a GUI
window = tk.Tk()
window.title('Tkinter GUI Open File Dialog')
window.resizable(False, False)
window.geometry('300x150')
# %% open file button
open_button = ttk.Button(window, text='Open a File',command=open_file)
open_button.grid(column=0, row=1, sticky='w', padx=10, pady=10)
# %% run window - automatic closing after 10 seconds
window.after(10000, window.destroy)
window.mainloop()
if filename: # check if filename was really selected
print('selected:', filename)
else:
print("you didn't select filename")
如果你想保持所有功能,那么它可能需要global在所有功能中使用
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
def get_filename():
global filename
filename = None # default value in global variable
# %% create a command associated to the window button
def open_file():
global filename # inform function to use global variable instead of local one
initialDir = '/'
fileTypes = (('Text files', '*.txt'), ('Csv files', '*.csv'), ('All files', '*.*'))
Title = 'Choose a file'
# use askopenfilename instead of askopenfile to get only name
filename = fd.askopenfilename(title=Title, filetypes=fileTypes)
window.destroy()
# %% create a GUI
window = tk.Tk()
window.title('Tkinter GUI Open File Dialog')
window.resizable(False, False)
window.geometry('300x150')
# %% open file button
open_button = ttk.Button(window, text='Open a File',command=open_file)
open_button.grid(column=0, row=1, sticky='w', padx=10, pady=10)
# %% run window - automatic closing after 10 seconds
window.after(10000, window.destroy)
window.mainloop()
return filename
# --- main ---
filename = get_filename()
if filename: # check if filename was really selected
print('selected:', filename)
else:
print("you didn't select filename")
流行的方法也是創建主視窗,隱藏它,直接運行askopenfilename無按鈕
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
def get_filename():
global filename
filename = None # default value in global variable
# %% create a command associated to the window button
def open_file():
global filename # inform function to use global variable instead of local one
initialDir = '/'
fileTypes = (('Text files', '*.txt'), ('Csv files', '*.csv'), ('All files', '*.*'))
Title = 'Choose a file'
# use askopenfilename instead of askopenfile to get only name
filename = fd.askopenfilename(title=Title, filetypes=fileTypes)
window.destroy()
# %% create a GUI
window = tk.Tk()
#window.iconify() # minimize to icon
window.withdraw() # hide it
window.after(10000, window.destroy)
open_file()
window.mainloop()
return filename
# --- main ---
filename = get_filename()
if filename: # check if filename was really selected
print('selected:', filename)
else:
print("you didn't select filename")
編輯:
可以帶引數運行的精簡版
import tkinter as tk
from tkinter import filedialog
def get_filename(title='Choose a file', directory='/', file_types = (('Text files', '*.txt'), ('Csv files', '*.csv'), ('All files', '*.*'))):
window = tk.Tk()
#window.iconify() # minimize to icon
window.withdraw() # hide it
filename = filedialog.askopenfilename(title=title, initialdir=directory, filetypes=file_types)
window.destroy()
return filename
# --- main ---
filename = get_filename(directory='/')
if filename: # check if filename was really selected
print('selected:', filename)
else:
print("you didn't select filename")
uj5u.com熱心網友回復:
編輯Furas提出的解決方案,以下代碼可能代表UiGetFile Matlab 函式的 Python 版本。唯一的缺點是檔案對話框的奇怪行為,有時出現在前臺,有時出現在后臺(使用 Spyder 5)。
import tkinter as tk
from tkinter import filedialog
def UiGetFile(fileDialogTitle='Select the file to open', initialDirectory='/', fileTypes = (('Text files', '*.txt'), ('Csv files', '*.csv'), ('All files', '*.*'))):
filePath = []
fileName = []
window = tk.Tk()
#window.iconify() # minimize to icon
window.withdraw() # hide it
fullname = filedialog.askopenfilename(title=fileDialogTitle, initialdir=initialDirectory, filetypes=fileTypes)
window.destroy()
if fullname:
allIndices = [i for i, val in enumerate(fullname) if val == '/']
filePath = fullname[0 : 1 max(allIndices)]
fileName = fullname[1 max(allIndices) : ]
return filePath, fileName
# --- main ---
fullname = UiGetFile()
print('File path: ', fullname[0])
print('File name: ', fullname[1])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441026.html
上一篇:將新影像放置在新的網格位置
