tkinter messagebox and filedialog

Tkinter MessageBox And FileDialog

Python Tkinter Tutorial- Part 3

In this last part of the Tkinter Tutorial Series, you will overlook two new features that can be implemented with help of Tkinter. Tkinter Messagebox and Filedialog are the commonly used Tkinter libraries. MessageBox is used to provide a feedback message for using any Tkinter Widget whereas Filedialog allows you to open any file from your local repository.

Tkinter MessageBox

Tkinter MessageBox is used to provide feedback in your GUI application. For better user experience you should provide proper feedback to your user at the time of error and a successful message.

Syntax:
from tkinter import messagebox
messagebox.method(heading,message)

Overview Of MessageBox Methods

showinfo()

Most of the time you need to provide feedback to your users. This feedback might be any information such as a user has successfully login, a message regarding the data is saved, the file saved in the directory, and many more. Tkinter message box provides a method showinfo() to display a message.

from tkinter import messagebox
import tkinter

root = tkinter.Tk()
root.geometry("200x200")

def click():
    messagebox.showinfo("Success","You are Anime Fan")

btn = tkinter.Button(text="Weeb",command=click).pack()
root.mainloop()

showerror()

Most of the time, a user might go wrong and should be provided with a proper error message. With help of messagebox.showerror() you can provide an error message whenever the user has encountered some error.

from tkinter import messagebox
import tkinter

root = tkinter.Tk()
root.geometry("200x200")

def click():
    messagebox.showerror("Invalid","Not verified")


btn = tkinter.Button(text="Check",command=click).pack()
root.mainloop()

askyesnocancel()

askyesnocancel() methods prompt the user to choose any one of the three options. If the user chooses Yes or No, then the return data type is Boolean. If in case user hits cancel then it returns None.

>>> messagebox.askyesnocancel("One Piece","Have You Watched It?")
False
>>> messagebox.askyesnocancel("One Piece","Have You Watched It?")
True
>>> messagebox.askyesnocancel("One Piece","Have You Watched It?")
None
from tkinter import messagebox
import tkinter

root = tkinter.Tk()
root.geometry("400x400")

def click():
    prompt = messagebox.askyesnocancel("What you choose","1-Yes, 0-No, None-Cancel")
    messagebox.showinfo("User Prompt",prompt)


btn = tkinter.Button(text="Check",command=click).pack()
root.mainloop()

There are some similar methods available in Tkinter Messagebox that you may explore. Remember that the syntax is the same. Try messagebox.askquestion(), messagebox.askyesno() methods.

Tkinter Filedialog

Tkinter Filedialog helps you to upload the file in Tkinter Application.

from tkinter import filedialog
messagebox.method(heading,message)

Overview Of Filedialog Methods

askopenfile()

As the name goes askopenfile(), lets the user open a file from their local system.

from tkinter import filedialog
import tkinter as tk

def open_file():
    file = filedialog.askopenfile()
    print(file)
    print(file.name)
    print(type(file))

root = tk.Tk()
btn = tk.Button(text="Open files",command=open_file).pack()
root.mainloop()
Output:
<_io.TextIOWrapper name="/home/lucifertrj/your_file" mode='r' encoding='UTF-8'>
/home/lucifertrj/your_file
<class '_io.TextIOWrapper'>

In the above example, we have created a simple GUI. On the button click, a pop-up window appears that lets the user open a file. And if you check the type of the file, it belongs to TextIOWrapper. But despite opening the file using askopenfile method, you can’t directly use this as the file path. Since the file is in UTF encoding mode, you need to access to file name attribute i.e., file.name to access the file path.

Note: We will use the same root window and button to check different filedialog methods.

askopenfilename()

In askopenfile() we saw that the file open was encoded in UTF-8 and we need to provide file.name to access the actual file path. But using askopenfilename() you can directly assign the file path

def open_file():
    file = filedialog.askopenfilename()
    print(file)
    print(type(file))
Output:
/home/python_book/python_tkinter.py

An Example To Use Tkinter MessageBox and FileDialog Together

from tkinter import filedialog,messagebox
import tkinter as tk
from PIL import Image

def open_file():
    file = filedialog.askopenfilename()
    filename,extension = file.split(".")
    #check for valid image extension
    if extension not in ['jpg','jpeg','biff','png','webp']:
        #display error message on invalid image extension
        messagebox.showerror("Invalid","Enter A Valid Image")
    else:
        #if the image is valid i.e.,
        #if it is in png, jpg, webp or biff
        #then open Image with PIL,
        img = Image.open(file)
        img.show()
        #displays success message
        messagebox.showinfo("Success","Image Opened")

root = tk.Tk()
root.geometry("200x200")
#fixed GUI- learn in ProTip
root.resizable(False,False)
btn = tk.Button(text="Open An Image",command=open_file,bg="black",fg="green",font=("Arial",18,"bold")).place(x=-1,y=60)
root.mainloop()

askdirectory()

def open_file():
    file = filedialog.askdirectory()
    print(file)
    print(type(file))
Output:
/home/lucifertrj/any_dir
<class 'str'>

Notice the type of the file is String.

Fixed GUI Dimensions

In order to keep the geometry fixed, you can neither minimize nor maximize the screen. There are two such ways you can accomplish it. Warning, here we might be sharing two ways, but there are many unique programmers, who might have some other ways as well. Remember there will always be many ways to write the same code in diverse ways.

Resizeable

import tkinter as tk
root = tk.Tk()
root.geometry("200x200")
root.resizable(False,False) #fixed GUI
#width-xaxis = False, height-yaxis = False
text1 = tk.Label(text="1st way for fixed GUI").pack()
root.mainloop()

Maxsize And Minsize

import tkinter as tk
root = tk.Tk()
root.geometry("200x200")
root.minsize(200,200) #fixed GUI
root.maxsize(200,200) #fixed GUI
text1 = tk.Label(text="2nd way for fixed GUI").pack()
root.mainloop()

Okay with this I conclude the Python Tkinter Tutorial Series, up next try out an exciting project i.e., Create A Pomodoro GUI App.

Subscribe to our Newsletter to never miss out on the content: https://animevyuh.org/newsletter. Join our Newsletter now for amazing Anime recommendationsPython, and Machine Learning Content.

Support Us: https://www.buymeacoffee.com/trjtarunhttps://ko-fi.com/tarunrjain751.
GitHub: https://github.com/lucifertrj.
Twitter: https://twitter.com/TRJ_0751.

Want to learn Machine Learning with Proper Roadmap and resource check this Repository: https://github.com/lucifertrj/100DaysOfML

1 thought on “Tkinter MessageBox And FileDialog”

  1. Pingback: Pomodoro GUI App

Comments are closed.