Tkfiledialog python 3 установка

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.

Источник

tkinter filedialog

tkFileDialog is a module with open and save dialog functions. Instead of implementing those in Tkinter GUI on your own.

This page is a collection of python tkinter file dialogs. The code is displayed here along with screenshots. Dialogs included in tkinter let you ask for a filename or directory.

tkinter file dialogs are easy to use, but not that easy to find out how to use. The main problem is that there is no simple example of how to do it. This article tries to fill the gap.

Related course:

Tkinter Open File

The askopenfilename function to creates an file dialog object. The extensions are shown in the bottom of the form (Files of type).

tkinter.tk.askopenfilename is an extension of the askopenfilename function provided in Tcl/Tk.

The code below will simply show the dialog and return the filename. If a user presses cancel the filename is empty. On a Windows machine change the initialdir to “C:\”.

Python 2.7 version:

from Tkinter import *from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

root = Tk()
root.filename = tkFileDialog.askopenfilename(initialdir = «/»,title = «Select file»,filetypes = ((«jpeg files»,«*.jpg»),(«all files»,«*.*»)))
print (root.filename)

Python 3 version:

from tkinter import filedialog
from tkinter import *

root = Tk()
root.filename = filedialog.askopenfilename(initialdir = «/»,title = «Select file»,filetypes = ((«jpeg files»,«*.jpg»),(«all files»,«*.*»)))
print (root.filename)

Here is an example (on Linux):

tkfiledialog Tkinter askopenfilename

tkfiledialog Tkinter askopenfilename

Tkinter Save File

The asksaveasfilename function prompts the user with a save file dialog.

Python 2.7 version

from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

root = Tk()
root.filename = tkFileDialog.asksaveasfilename(initialdir = «/»,title = «Select file»,filetypes = ((«jpeg files»,«*.jpg»),(«all files»,«*.*»)))
print (root.filename)

Python 3 version

from tkinter import filedialog
from tkinter import *

root = Tk()
root.filename = filedialog.asksaveasfilename(initialdir = «/»,title = «Select file»,filetypes = ((«jpeg files»,«*.jpg»),(«all files»,«*.*»)))
print (root.filename)

Tkinter Open Directory

Consider a scenario where your program needs to get a directory, the user clicked on the ok button and now you want to determine the path.

The askdirectory presents the user with a popup for directory selection.

Python 2.7 version

from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
root = Tk()
root.directory = tkFileDialog.askdirectory()
print (root.directory)

tkinter-askdirectory

If you are new to programming Tkinter, I highly recommend this course.

Источник

Python-сообщество

[RSS Feed]

  • Начало
  • » Python для новичков
  • » python 3, tkfiledialog отсутствует?

#1 Ноя. 26, 2012 09:04:06

python 3, tkfiledialog отсутствует?

не нашёл в третьем питоне (3.3) модуля tkFileDialog. он там отсутствует?
подскажите инструмент для созания диалоговых окон для выбора файла/папки

#2 Ноя. 26, 2012 10:52:26

python 3, tkfiledialog отсутствует?

file = tkinter.filedialog.askopenfile() # возвращает обект файл, с которым уже дальше можно работать data = file.read() 

#3 Апрель 17, 2014 00:36:41

python 3, tkfiledialog отсутствует?

Здравствуйте!
Скажите, а если я хочу сделать такую операцию from tkinter.filedialog import * как быть? Выдаёт ошибку ImportError: No module named filedialog но раз работает tkinter.filedialog.askopenfile(), значит подмодуль tkinter.filedialog есть. Как оттуда всё импортировать?

#4 Апрель 17, 2014 06:27:31

python 3, tkfiledialog отсутствует?

такой импорт не желателен в питоне. необходимо импортировать либо сам модуль, либо то что вам нужно

>>> from tkinter.filedialog import askopenfile >>> askopenfile function askopenfile at 0x7f8a38e48950> >>> 

Отредактировано ilnur (Апрель 17, 2014 06:55:58)

Источник

ImportError: No module named tkFileDialog

Hi With every piece of code i download to check out, i often find with python 3.1/Windows Vista that the code will start with from Tkinter import * but i need to change it to
from tkinter import * as it seems to be case sensative, i tried renameing the directory to be Tkinter but it didn’t work, so i left it as it was and just changed the code each time .. annoying but oh well. In my next program i wanted an open dialogue which needed the «from tkFileDialog import *» but i get a module not found, renaming it to lower case like i do with others does not change anything. I thought maybe was one to download but google shows me example code, docs etc but no download leading me to believe i already have it but it can’t be fouind due to the same kinda issue .. CAUSE i found a python script called «file dialogue.py» (and another file) IN the lib/tkinter folder. Anyone with windows knows any workarounds for this issue . this module naming and case sensative stuff is getting annoying.

  • 5 Contributors
  • 6 Replies
  • 12K Views
  • 1 Year Discussion Span
  • Latest Post 12 Years Ago Latest Post by jgomo3
>>> import tkinter as tk >>> print(tk.filedialog.__doc__) File selection dialog classes. Classes: - FileDialog - LoadFileDialog - SaveFileDialog This module also presents tk common file dialogues, it provides interfaces to the native file dialogues available in Tk 4.2 and newer, and the directory dialogue available …

if it worked, then I would believe you can import that module like any other in python. I do not use Tk but I use python.. That would be my limited knowledge..

All 6 Replies

>>> import tkinter as tk >>> print(tk.filedialog.__doc__) File selection dialog classes. Classes: - FileDialog - LoadFileDialog - SaveFileDialog This module also presents tk common file dialogues, it provides interfaces to the native file dialogues available in Tk 4.2 and newer, and the directory dialogue available in Tk 8.3 and newer. These interfaces were written by Fredrik Lundh, May 1997. # Give you a list of method under tk >>>dir(tk)

Yeah that worked, i typed that commands in IDLE and everything happened the same, so that means i do have the filedialogue module? What now? how do i get it open in my code so i can use it?

if it worked, then I would believe you can import that module like any other in python. I do not use Tk but I use python.. That would be my limited knowledge..

# use Tkinter's file dialog window to get # a file name with full path, you can also use # this to get filenames for a console program # askopenfilename() gives one selected filename # with Python25 use . #import Tkinter as tk #from tkFileDialog import askopenfilename # with Python30 use . import tkinter as tk from tkinter.filedialog import askopenfilename root = tk.Tk() # show askopenfilename dialog without the Tkinter window root.withdraw() # default is all file types file_name = askopenfilename() print(file_name)

With the advent of Python3 Tkinter has turned into a package called tkinter. I usually add a try/except to pick the right import:

# a simple Tkinter number guessing game # shows how to create a window, an entry, a label, a button, # a button mouse click response, and how to use a grid for layout import random try: # for Python2 import Tkinter as tk except ImportError: # for Python3 import tkinter as tk def click(): """the mouse click command response""" global rn # get the number from the entry area num = int(enter1.get()) # check it out if num > rn: label2['text'] = str(num) + " guessed too high!" elif num < rn: label2['text'] = str(num) + " guessed too low!" else: s1 = str(num) + " guessed correctly!" s2 = "\n Let's start a new game!" label2['text'] = s1 + s2 # pick a new random number rn = random.randrange(1, 11) enter1.delete(0, 2) # create the window and give it a title root = tk.Tk() root.title("Heidi's Guess A Number Game") # pick a random integer from 1 to 10 rn = random.randrange(1, 11) # let the user know what is going on label1 = tk.Label(root, text="Guess a number between 1 and 10 -->") # layout this label in the specified row and column of the grid # also pad with spaces along the x and y direction label1.grid(row=1, column=1, padx=10, pady=10) # this your input area enter1 = tk.Entry(root, width=5, bg='yellow') enter1.grid(row=1, column=2, padx=10) # put the cursor into the entry field enter1.focus() # action button, right-click it to execute command button1 = tk.Button(root, text=" Press to check the guess ", command=click) button1.grid(row=2, column=1, columnspan=2, padx=10, pady=10) # the result displays here label2 = tk.Label(root, text="", width=50) label2.grid(row=3, column=1, columnspan=2, pady=10) # start the mouse/keyboard event loop root.mainloop()

Источник

Читайте также:  Распознаватель речи на питоне
Оцените статью