Thursday, February 7, 2019

tkinter example 13 - (Dialog)

Dialogs

Usually programs have dialog boxes that allow the user to pick a file to open or to save a file. Tkinter provides the module filedialog for this purpose. To use them in Tkinter, we need the following import statement:

from tkinter.filedialog import * or from tkinter import filedialog

Tkinter dialogs usually look like the ones that are native to the operating system. The following program creates a dialog which allows you to open a file from the directory:

from tkinter import *
from tkinter.filedialog import *

from tkinter import filedialog

master = Tk()

master.title('File dialog')

def callback():
    name= filedialog.askopenfilename()
    print (name)
 
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()

The output of the program is shown below:





When we click on File Open button a new dialog appears as shown below from where we can select the desired file to be opened:



Some of the most useful dialogs are:
  1. askopenfilename - Opens a typical file chooser dialog
  2. askopenfilenames - Like previous, but user can pick more than one file
  3. asksaveasfilename - Opens a typical file save dialog
  4. askdirectory - Opens a directory chooser dialog


The return value of askopenfilename and asksaveasfilename is the name of the file selected.
There is no return value if the user does not pick a value. The return value of askopenfilenames
is a list of files, which is empty if no files are selected. The askdirectory function returns the
name of the directory chosen.

There are some options you can pass to these functions. You can set initialdir to the directory
you want the dialog to start in. You can also specify the file types. Here is an example:
filename=askopenfilename(initialdir='c:\\python31\\', filetypes=[('Image files', '.jpg .png .gif'),
('All files', '*')])

The following program opens a file dialog that allows you to select a text file. The program then displays the contents of the file in a textbox. See the code below:

from tkinter import *
from tkinter.filedialog import *
from tkinter.scrolledtext import ScrolledText
root = Tk()
root.title('File dialog') 
textbox = ScrolledText()
textbox.grid()

filename=askopenfilename(initialdir='C:\Python_Code\examples',filetypes=[('Text files', '.txt'),('All files', '*')])
s = open(filename).read()
textbox.insert(1.0, s)
mainloop()

The output of the program is shown below:



Once we select the file (in our case cities.txt) and click Open, the file opens as shown below:



 

Try to use the other options shown above in your programs to understand their functionality. I'll end this post now and till we meet next, keep learning and practicing Python as Python is easy to learn!
Share:

0 comments:

Post a Comment