Окно загрузки файла python

Окно загрузки файла python

Tkinter обладает рядом встроенных диалоговых окон для различных задач. Рассмотрим некоторые из них.

filedialog

Модуль filedialog предоставляет функциональность файловых диалоговых окон, которые позволяют выбрать файл или каталог для различных задач. В частности в модуле для работы с файлами определены следующие функции:

  • askopenfilename() : открывает диалоговое окно для выбора файла и возвращает путь к выбранному файлу. Если файл не выбран, возвращается пустая строка «»
  • askopenfilenames() : открывает диалоговое окно для выбора файлов и возвращает список путей к выбранным файлам. Если файл не выбран, возвращается пустая строка «»
  • asksaveasfilename() : открывает диалоговое окно для сохранения файла и возвращает путь к сохраненному файлу. Если файл не выбран, возвращается пустая строка «»
  • asksaveasfile() : открывает диалоговое окно для сохранения файла и возвращает сохраненный файл. Если файл не выбран, возвращается None
  • askdirectory() : открывает диалоговое окно для выбора каталога и возвращает путь к выбранному каталогу. Если файл не выбран, возвращается пустая строка «»
  • askopenfile() : открывает диалоговое окно для выбора файла и возвращает выбранный файл. Если файл не выбран, возвращается None
  • askopenfiles() : открывает диалоговое окно для выбора файлов и возвращает список выбранных файлов

Рассмотрим открытие и сохранение файла на примере:

from tkinter import * from tkinter import ttk from tkinter import filedialog root = Tk() root.title("METANIT.COM") root.geometry("250x200") root.grid_rowconfigure(index=0, weight=1) root.grid_columnconfigure(index=0, weight=1) root.grid_columnconfigure(index=1, weight=1) text_editor = Text() text_editor.grid(column=0, columnspan=2, row=0) # открываем файл в текстовое поле def open_file(): filepath = filedialog.askopenfilename() if filepath != "": with open(filepath, "r") as file: text =file.read() text_editor.delete("1.0", END) text_editor.insert("1.0", text) # сохраняем текст из текстового поля в файл def save_file(): filepath = filedialog.asksaveasfilename() if filepath != "": text = text_editor.get("1.0", END) with open(filepath, "w") as file: file.write(text) open_button = ttk.Button(text="Открыть файл", command=open_file) open_button.grid(column=0, row=1, sticky=NSEW, padx=10) save_button = ttk.Button(text="Сохранить файл", command=save_file) save_button.grid(column=1, row=1, sticky=NSEW, padx=10) root.mainloop()

Открытие и сохранение файлов в Tkinter и Python

Здесь определены две кнопки. По нажатию по на кнопку open_button вызывается функция filedialog.askopenfilename() . Она возвращает путь к выбранному файлу. И если в диалоговом окне не нажата кнопка отмены (то есть путь к файлу не равен пустой строке), то считываем содержимое текстового файла и добавляем его в виджет Text

def open_file(): filepath = filedialog.askopenfilename() if filepath != "": with open(filepath, "r") as file: text =file.read() text_editor.delete("1.0", END) text_editor.insert("1.0", text)

По нажатию на кнопку save_button срабатывает функция filedialog.asksaveasfilename() , которая возвращает путь к файлу для сохранения текста из виджета Text. И если файл выбран, то открываем его и сохраняем в него текст:

def save_file(): filepath = filedialog.asksaveasfilename() if filepath != "": text = text_editor.get("1.0", END) with open(filepath, "w") as file: file.write(text)

Эти функции могут принимать ряд параметров:

  • confirmoverwrite : нужно ли подтверждение для перезаписи файла (для диалогового окна сохранения файла)
  • defaultextension : расширение по умолчанию
  • filetypes : шаблоны типов файлов
  • initialdir : стартовый каталог, который открывается в окне
  • initialfile : файл по умолчанию
  • title : заголовок диалогового окна
  • typevariable : переменная, к которой привязан выбранный файл
filedialog.askopenfiles(title="Выбор файла", initialdir="D://tkinter", defaultextension="txt", initialfile="hello.txt")

Выбор шрифта

from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") label = ttk.Label(text="Hello World") label.pack(anchor=NW, padx=10, pady=10) def font_changed(font): label["font"] = font def select_font(): root.tk.call("tk", "fontchooser", "configure", "-font", label["font"], "-command", root.register(font_changed)) root.tk.call("tk", "fontchooser", "show") open_button = ttk.Button(text="Выбрать шрифт", command=select_font) open_button.pack(anchor=NW, padx=10, pady=10) root.mainloop()

По нажатию на кнопку вызывается функция select_font, в которой вначале производится настройка диалогового окна установки шрифта

root.tk.call("tk", "fontchooser", "configure", "-font", label["font"], "-command", root.register(font_changed))

В частности, значение «configure» указывает, что в данном случае производится настройка диалогового окна. Аргумент «-font» указывает, что следующее значение представляет настройка шрифта, который будет выбран в диалоговом окне по умолчанию. В качестве такового здесь используется шрифт метки label.

Аргумент «-command» указывает, что дальше идет определение функции, которая будет срабатывать при выборе шрифта. Здесь такой функцией является функция font_changed . Функция выбора шрифта должна принимать один параметр — через него будет передаваться выбранный шрифт. В данном случае просто переустанавливаем шрифт метки.

Для отображения окна выбора шрифта выполняется вызов

root.tk.call("tk", "fontchooser", "show")

Таким образом, при нажатии на кнопку откроется окно выбора шрифта, а после его выбора он будет применен к метке:

выбор шрифта в Tkinter и Python

Выбор цвета

Для выбора цвета применяется функции из модуля colorchooser.askcolor() :

from tkinter import * from tkinter import ttk from tkinter import colorchooser root = Tk() root.title("METANIT.COM") root.geometry("250x200") label = ttk.Label(text="Hello World") label.pack(anchor=NW, padx=10, pady=10) def select_color(): result = colorchooser.askcolor(initialcolor="black") label["foreground"] = result[1] open_button = ttk.Button(text="Выбрать цвет", command=select_color) open_button.pack(anchor=NW, padx=10, pady=10) root.mainloop()

Здесь по нажатию на кнопку вызывается функция select_color. В этой функции вызывается функция colorchooser.askcolor . С помощью параметра initialcolor устанавливаем цвет, который выбран по умолчанию в диалоговом окне. В данном случае это черный цвет («black»)

Результатом функции является кортеж с определениями выбранного цвета. Например, для красного цвета кортеж будет выглядеть следующим образом: ((255, 0, 0), «#ff0000») . То есть, обратившись к второму элементу кортежа, можно получить шестнадцатиричное значение цвета. Здесь выбранный цвет применяется для установки цвета шрифта метки:

Источник

Tkinter Open File Dialog

Summary: in this tutorial, you’ll learn how to show an open file dialog in Tkinter applications.

Introduction to the Tkinter Open File Dialog functions

When developing a Tkinter application that deals with the file system, you need to provide a dialog that allows file selections.

To do that, you can use the tkinter.filedialog module. The following steps show how to display an open file dialog:

First, import the tkinter.filedialog module:

from tkinter import filedialog as fdCode language: Python (python)

Second, call the fd.askopenfilename() function to show a dialog that allows a single file selection:

filename = fd.askopenfilename()Code language: Python (python)

The askopenfilename() function returns the file name that you selected.

The askopenfilename() also supports other useful options including the initial directory displayed by the dialog or filtering files by their extensions.

The following program displays a button:

If you click the button, it’ll open a file dialog:

After you select a file, the program will show the full path of the selected file:

import tkinter as tk from tkinter import ttk from tkinter import filedialog as fd from tkinter.messagebox import showinfo # create the root window root = tk.Tk() root.title('Tkinter Open File Dialog') root.resizable(False, False) root.geometry('300x150') def select_file(): filetypes = ( ('text files', '*.txt'), ('All files', '*.*') ) filename = fd.askopenfilename( title='Open a file', initialdir='/', filetypes=filetypes) showinfo( title='Selected File', message=filename ) # open button open_button = ttk.Button( root, text='Open a File', command=select_file ) open_button.pack(expand=True) # run the application root.mainloop() Code language: Python (python)

Selecting multiple files

The askopenfilenames() function displays a file dialog for multiple file selections. It returns the selected file names as a tuple. For example:

import tkinter as tk from tkinter import ttk from tkinter import filedialog as fd from tkinter.messagebox import showinfo # create the root window root = tk.Tk() root.title('Tkinter File Dialog') root.resizable(False, False) root.geometry('300x150') def select_files(): filetypes = ( ('text files', '*.txt'), ('All files', '*.*') ) filenames = fd.askopenfilenames( title='Open files', initialdir='/', filetypes=filetypes) showinfo( title='Selected Files', message=filenames ) # open button open_button = ttk.Button( root, text='Open Files', command=select_files ) open_button.pack(expand=True) root.mainloop()Code language: Python (python)

Opening files directly

After getting the selected file names, you can open them using the open() method.

To make it more convenient, the tkinter.filedialog module also provides some functions that allow you to select one or more files and return the file objects directly.

The askopenfile() function displays a file dialog and returns a file object of the selected file:

f = fd.askopenfile()Code language: Python (python)

And the askopenfiles() function shows a file dialog and returns file objects of the selected files:

f = fd.askopenfiles()Code language: Python (python)

The following program illustrates how to use the askopenfile() function:

It’ll allow you to open a text file and display the file content on a Text widget:

import tkinter as tk from tkinter import ttk from tkinter import filedialog as fd # Root window root = tk.Tk() root.title('Display a Text File') root.resizable(False, False) root.geometry('550x250') # Text editor text = tk.Text(root, height=12) text.grid(column=0, row=0, sticky='nsew') def open_text_file(): # file type filetypes = ( ('text files', '*.txt'), ('All files', '*.*') ) # show the open file dialog f = fd.askopenfile(filetypes=filetypes) # read the text file and show its content on the Text text.insert('1.0', f.readlines()) # open file button open_button = ttk.Button( root, text='Open a File', command=open_text_file ) open_button.grid(column=0, row=1, sticky='w', padx=10, pady=10) root.mainloop()Code language: Python (python)

Summary

  • Use the askopenfilename() function to display an open file dialog that allows users to select one file.
  • Use the askopenfilenames() function to display an open file dialog that allows users to select multiple files.
  • Use the askopenfile() or askopenfiles() function to display an open file dialog that allows users to select one or multiple files and receive a file or multiple file objects.

Источник

Читайте также:  Тег SUP
Оцените статью