a Python GUI-based random quote generator

Here’s a Python program that uses tkinter to create a GUI-based random quote generator.

The quotes are stored in a CSV file, which the program reads to display a random quote each time the “Show Random Quote” button is clicked.

Code

CSV file

First, create a CSV file named quotes.csv with the following contents. Each row should contain a quote and the author:

quote,author
"The only limit to our realization of tomorrow is our doubts of today.",Franklin D. Roosevelt
"Do not wait to strike till the iron is hot; but make it hot by striking.",William Butler Yeats
"Whether you think you can or think you can’t, you’re right.",Henry Ford
"The future belongs to those who believe in the beauty of their dreams.",Eleanor Roosevelt
"It does not matter how slowly you go as long as you do not stop.",Confucius
"Act as if what you do makes a difference. It does.",William James
"Success is not how high you have climbed, but how you make a positive difference to the world.",Roy T. Bennett
"Life is 10% what happens to us and 90% how we react to it.",Charles R. Swindoll
"The best way to predict the future is to create it.",Peter Drucker
"You miss 100% of the shots you don’t take.",Wayne Gretzky

Python Code

Now, here’s the Python code for the program:

import tkinter as tk
import random
import csv

# Function to load quotes from CSV file
def load_quotes(filename):
    quotes = []
    with open(filename, newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        next(reader)  # Skip header row
        for row in reader:
            quote, author = row
            quotes.append((quote, author))
    return quotes

# Function to display a random quote
def show_random_quote():
    quote, author = random.choice(quotes)
    quote_label.config(text=f'"{quote}"')
    author_label.config(text=f'- {author}')

# Load quotes from CSV file
quotes = load_quotes('quotes.csv')

# Initialize the main window
root = tk.Tk()
root.title("Random Quote Generator")
root.geometry("400x200")

# Title Label
title_label = tk.Label(root, text="Random Quote Generator", font=("Helvetica", 16))
title_label.pack(pady=10)

# Quote Label
quote_label = tk.Label(root, text="", wraplength=350, font=("Helvetica", 12), justify="center")
quote_label.pack(pady=10)

# Author Label
author_label = tk.Label(root, text="", font=("Helvetica", 10, "italic"), justify="center")
author_label.pack()

# Button to display a random quote
random_quote_button = tk.Button(root, text="Show Random Quote", command=show_random_quote)
random_quote_button.pack(pady=10)

# Run the main loop
root.mainloop()

Explanation

  1. Import Required Libraries:
    • tkinter: Used to create the GUI components.
    • random: Used to select a random quote from the list.
    • csv: Used to read quotes from a CSV file.
  2. Function to Load Quotes (load_quotes):
    • This function reads the quotes from a CSV file and stores them as a list of tuples.
    • with open(filename, newline=”, encoding=’utf-8′) as csvfile: Opens the file with UTF-8 encoding, handling any special characters.
    • reader = csv.reader(csvfile): Creates a CSV reader object to iterate through each row.
    • next(reader): Skips the header row in the CSV.
    • quotes.append((quote, author)): Each quote and author is added as a tuple to the quotes list.
    • The function returns the list of quotes.
  3. Function to Display a Random Quote (show_random_quote):
    • quote, author = random.choice(quotes): Selects a random tuple (quote, author) from the quotes list.
    • quote_label.config(text=f'”{quote}”‘): Updates quote_label to display the randomly selected quote.
    • author_label.config(text=f’- {author}’): Updates author_label to display the author’s name.
  4. Load Quotes from the CSV File:
    • quotes = load_quotes(‘quotes.csv’): Calls load_quotes() to load all quotes from the quotes.csv file.
  5. Initialize the Main Application Window:
    • root = tk.Tk(): Creates the main application window.
    • root.title(“Random Quote Generator”): Sets the title of the window.
    • root.geometry(“400×200”): Sets the window size to 400×200 pixels.
  6. Title Label:
    • title_label = tk.Label(…): Displays the title of the application at the top of the window.
  7. Quote and Author Labels:
    • quote_label = tk.Label(…): Displays the quote in the center of the window.
    • wraplength=350: Wraps the text if it exceeds 350 pixels in width.
    • author_label = tk.Label(…): Displays the author’s name below the quote in italics.
  8. Random Quote Button:
    • random_quote_button = tk.Button(…): Creates a button labeled “Show Random Quote”.
    • command=show_random_quote: Specifies that show_random_quote should be called when the button is clicked.
  9. Run the Main Event Loop:
    • root.mainloop(): Starts the tkinter main event loop, keeping the application window open and responsive to user actions.

Usage

  1. Open the Application:
    • The user opens the application window and sees the title “Random Quote Generator” and a button labeled “Show Random Quote”.
  2. Show a Random Quote:
    • When the user clicks the button, a random quote along with the author’s name is displayed in the window.

Sample Output

When you click the “Show Random Quote” button, the output might look like this:

"The best way to predict the future is to create it."
- Peter Drucker

Notes

  • File Path: Ensure that quotes.csv is in the same directory as the Python script, or provide the full path to the file.
  • Adding More Quotes: You can easily add more quotes to the CSV file. Just make sure each row has a quote and an author separated by a comma.
  • Error Handling: This example assumes the CSV file is well-formed. In a production scenario, you might want to add error handling for file I/O and CSV parsing errors.

Summary

This Python program uses tkinter to create a GUI-based random quote generator.

It reads quotes from a quotes.csv file and displays a random quote and author when the user clicks the “Show Random Quote” button.

This is a simple yet effective way to practice using CSV files, tkinter, and random selection in Python.

Related posts

BMI and BMR calculator using Tkinter

A Python program that generates a random password

A Python program that displays a random quote