Skip to content

Lesson 22 ยท Dialogs and Menus

File Dialogs, Color Chooser and simpledialog

Open and save files with Tkinter's filedialog, pick colors with colorchooser, ask for a single value with simpledialog, and handle Cancel correctly.

Besides message boxes, Tkinter includes dialogs that return data: the path of a file, a folder, a color, or a typed value. They are the standard way to open and save documents, so your program looks and feels like a native application, because on Windows and macOS the operating system's own file picker appears.

This lesson covers tkinter.filedialog, tkinter.colorchooser and tkinter.simpledialog. The dialog calls are read-only (they need a screen). The runnable blocks reproduce what you do with the return values: handling Cancel, building file type filters, and converting colors.

The file dialogs

Python
from tkinter import filedialog

path = filedialog.askopenfilename(
    title="Open a text file",
    initialdir=".",
    filetypes=[("Text files", "*.txt"), ("Python files", "*.py"), ("All files", "*.*")],
)
if path:
    with open(path, encoding="utf-8") as f:
        text = f.read()

A native "Open" window appears, listing only .txt files at first, with a drop-down to switch the filter. If the user chooses a file, path is a string like C:/Users/ana/notes.txt. If the user presses Cancel, path is an empty string "". Always test if path: before opening anything, otherwise open("") raises FileNotFoundError.

Function Returns
askopenfilename() one path (str) or ""
askopenfilenames() a tuple of paths (empty tuple on Cancel)
asksaveasfilename() a path for a file that need not exist, or ""
askdirectory() a folder path or ""
askopenfile() / asksaveasfile() an already opened file object, or None

The ...file variants return an open file; most programmers prefer the ...filename variants because they keep control over the encoding and the with block.

Useful options

  • title: the window caption.
  • initialdir: where the dialog starts. Remember the last folder the user used and pass it back.
  • initialfile: a suggested file name for Save As.
  • defaultextension=".txt": added automatically if the user types a name without an extension.
  • filetypes: a list of (label, pattern) pairs. Several patterns for one label go in a tuple: ("Images", ("*.png", "*.jpg")). On macOS the patterns are matched slightly differently, so always include an "All files" entry.
  • parent: the window that owns the dialog.
  • confirmoverwrite (Python 3.9+): False disables the "file already exists" question if you want to handle it yourself.
Python
path = filedialog.asksaveasfilename(
    defaultextension=".csv",
    filetypes=[("CSV file", "*.csv")],
    initialfile="report.csv",
)
if not path:
    return          # user cancelled

The color chooser

Python
from tkinter import colorchooser

rgb, hex_code = colorchooser.askcolor(color="#336699", title="Pick a brush color")
if hex_code:
    canvas_color = hex_code

A color wheel window appears, pre-set to #336699. askcolor returns a pair: an (r, g, b) tuple of ints (some platforms return floats) and a "#rrggbb" string. When cancelled, it returns (None, None), so test the second element. The hex string can go straight into any widget option such as bg= or fill=.

simpledialog: ask for one value

simpledialog shows a tiny window with a prompt and an entry. It also validates the type for you:

Python
from tkinter import simpledialog

name = simpledialog.askstring("Name", "Who are you?", parent=root)
age = simpledialog.askinteger("Age", "How old are you?", minvalue=0, maxvalue=130, parent=root)
price = simpledialog.askfloat("Price", "Price in dollars:", minvalue=0.0)

askinteger keeps the dialog open and shows an error message when the user types letters or a number outside the range. Each function returns None on Cancel. Note that 0 is a valid answer but is falsy, so write if age is not None:, not if age:.

simpledialog is fine for one question. For a form with several fields, a combo box and validation, write a custom dialog (Toplevel Windows and Custom Dialogs).

Handling Cancel everywhere

Every dialog above has a "nothing chosen" value, and each one is different:

What Cancel returns

File dialogs Empty string
askcolor (None, None)
simpledialog None
Message boxes False or None

Always test the result before using it.

1 / 2

The stand-in below is not Tkinter. It models these results with a fake "user" and builds the filter list the way the real dialog expects it.

Python Stand-in: handling Cancel and building file filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading and writing documents: a pattern

Most editors have the same two commands. Keep the current path in one variable; Save asks only when there is no path yet.

Python
class Editor:
    def __init__(self):
        self.path = None

    def open_file(self):
        path = filedialog.askopenfilename(filetypes=FILETYPES)
        if not path:
            return
        with open(path, encoding="utf-8") as f:
            self.text.delete("1.0", "end")
            self.text.insert("1.0", f.read())
        self.path = path

    def save(self):
        if self.path is None:
            return self.save_as()
        self.write(self.path)

    def save_as(self):
        path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=FILETYPES)
        if path:
            self.path = path
            self.write(path)

The window shows a text area and a File menu with Open, Save and Save As. The logic of path is None is plain Python, so you can check it away from the GUI:

Python Stand-in: Save vs Save As logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Not checking for Cancel. This is the number one crash in beginner file editors.
  • Hard-coding Windows paths with single backslashes. Tkinter returns forward slashes; use os.path or pathlib to work with them.
  • Using askopenfile and forgetting to close the file.
  • Opening files without encoding="utf-8"; the default depends on the platform.
  • Using if age: with askinteger, which treats 0 as Cancel.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does askopenfilename return when the user presses Cancel?

    The filename functions return '' on Cancel, so if path: is the right test.
  2. 2. How do you read the chosen color from askcolor?

    askcolor returns (rgb_tuple, '#rrggbb'), or (None, None) on Cancel.
  3. 3. Why is if age: wrong after simpledialog.askinteger?

    Cancel returns None, a real 0 is falsy as well, so you need age is not None.
  4. 4. Which option gives Save As a suggested extension?

    defaultextension is appended when the user types a name without an extension.

Summary

  • filedialog has open, save and directory pickers; Cancel gives "" (or an empty tuple, or None for the file-object variants).
  • colorchooser.askcolor returns (rgb, hex); Cancel gives (None, None).
  • simpledialog asks for one typed value and returns None on Cancel.
  • Provide filetypes with an "All files" entry and a defaultextension.
  • Keep the document path in one place so Save and Save As share logic.

Next: Menus and Menubuttons