Fibonacci Sequence in Python with Tkinter

Faraz

By Faraz - July 05, 2024

Learn how to create a Fibonacci sequence generator in Python using Tkinter for a graphical user interface. Step-by-step guide with code examples.


fibonacci-sequence-in-python-with-tkinter.webp

Table of Contents

  1. Setting Up Your Python Environment
  2. Step 1: Import Necessary Modules
  3. Step 2: Define the Fibonacci Function
  4. Step 3: Format the Fibonacci Sequence
  5. Step 4: Display the Fibonacci Sequence
  6. Step 5: Create the Tkinter GUI
  7. Full Fibonacci Sequence Source Code
  8. Conclusion and Next Steps

The Fibonacci sequence is a series of numbers where each number (after the first two) is the sum of the two preceding ones, usually starting with 0 and 1, the sequence goes 0,1,1,2,3,5,8,13,21,34, and so on. It's a popular sequence in mathematics and computer science due to its simplicity and the intriguing properties it exhibits. In this blog, we will create a Python application using Tkinter to generate and display the Fibonacci sequence up to a user-specified number of terms.

Setting Up Your Python Environment

Before we dive into the code, ensure you have Python installed on your system. You can download it from the official Python website.

Once installed, verify your installation by opening a command prompt or terminal and typing python --version.

Additionally, you'll need to install Tkinter if it's not already included in your Python distribution.

Tkinter is usually bundled with standard Python installations, but you can install it separately if needed using pip install tk.

Step 1: Import Necessary Modules

We will use the tkinter module for creating the graphical user interface (GUI) and messagebox for displaying error messages.

import tkinter as tk
from tkinter import messagebox

Step 2: Define the Fibonacci Function

The fibonacci function generates the Fibonacci sequence up to the nth number. It returns an empty list if the input is invalid (i.e., a negative integer).

def fibonacci(n):
    """Generate Fibonacci sequence up to the nth number."""
    if n < 0:
        messagebox.showerror("Input Error", "Please enter a positive integer.")
        return []
    fib_sequence = [0, 1]
    for i in range(2, n):
        fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
    return fib_sequence[:n]

Step 3: Format the Fibonacci Sequence

The format_fibonacci_sequence function formats the sequence for display in the Tkinter text widget.

def format_fibonacci_sequence(fib_sequence):
    """Format Fibonacci sequence for display."""
    formatted_sequence = []
    for i in range(2, len(fib_sequence)):
        formatted_sequence.append(f"{fib_sequence[i-2]} + {fib_sequence[i-1]} = {fib_sequence[i]}")
    return "\n".join(formatted_sequence)

Step 4: Display the Fibonacci Sequence

The display_fibonacci_sequence function retrieves the user input, generates the sequence, and displays it in the text widget.

def display_fibonacci_sequence():
    """Display Fibonacci sequence up to the user-specified number in the tkinter window."""
    try:
        n = int(entry.get())
        fib_sequence = fibonacci(n)
        if not fib_sequence:
            return

        formatted_sequence = format_fibonacci_sequence(fib_sequence)
        result_text.delete(1.0, tk.END)  # Clear previous content
        result_text.insert(tk.END, formatted_sequence)
    except ValueError:
        messagebox.showerror("Input Error", "Please enter a valid integer.")

Step 5: Create the Tkinter GUI

Now, we will create the Tkinter window, add a label, entry box, button, and text widget to display the Fibonacci sequence.

# Create a tkinter window
window = tk.Tk()
window.resizable(0,0)
window.title("Fibonacci Sequence")

# Create a label and entry to get user input
input_label = tk.Label(window, text="Enter the number of terms:")
input_label.pack()
entry = tk.Entry(window)
entry.pack()

# Create a button to generate and display the Fibonacci sequence
generate_button = tk.Button(window, text="Generate", command=display_fibonacci_sequence)
generate_button.pack()

# Create a frame to hold the text widget and scrollbar
frame = tk.Frame(window)
frame.pack()

# Create a text widget to display the sequence
result_text = tk.Text(frame, height=10, width=50, wrap=tk.WORD)
result_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

# Create a scrollbar and link it to the text widget
scrollbar = tk.Scrollbar(frame, command=result_text.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
result_text.config(yscrollcommand=scrollbar.set)

# Run the tkinter event loop
window.mainloop()

Full Fibonacci Sequence Source Code

import tkinter as tk
from tkinter import messagebox

def fibonacci(n):
    """Generate Fibonacci sequence up to the nth number."""
    if n < 0:
        messagebox.showerror("Input Error", "Please enter a positive integer.")
        return []
    fib_sequence = [0, 1]
    for i in range(2, n):
        fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
    return fib_sequence[:n]

def format_fibonacci_sequence(fib_sequence):
    """Format Fibonacci sequence for display."""
    formatted_sequence = []
    for i in range(2, len(fib_sequence)):
        formatted_sequence.append(f"{fib_sequence[i-2]} + {fib_sequence[i-1]} = {fib_sequence[i]}")
    return "\n".join(formatted_sequence)

def display_fibonacci_sequence():
    """Display Fibonacci sequence up to the user-specified number in the tkinter window."""
    try:
        n = int(entry.get())
        fib_sequence = fibonacci(n)
        if not fib_sequence:
            return

        formatted_sequence = format_fibonacci_sequence(fib_sequence)
        result_text.delete(1.0, tk.END)  # Clear previous content
        result_text.insert(tk.END, formatted_sequence)
    except ValueError:
        messagebox.showerror("Input Error", "Please enter a valid integer.")

# Create a tkinter window
window = tk.Tk()
window.resizable(0,0)
window.title("Fibonacci Sequence")

# Create a label and entry to get user input
input_label = tk.Label(window, text="Enter the number of terms:")
input_label.pack()

entry = tk.Entry(window)
entry.pack()

# Create a button to generate and display the Fibonacci sequence
generate_button = tk.Button(window, text="Generate", command=display_fibonacci_sequence)
generate_button.pack()

# Create a frame to hold the text widget and scrollbar
frame = tk.Frame(window)
frame.pack()

# Create a text widget to display the sequence
result_text = tk.Text(frame, height=10, width=50, wrap=tk.WORD)
result_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

# Create a scrollbar and link it to the text widget
scrollbar = tk.Scrollbar(frame, command=result_text.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
result_text.config(yscrollcommand=scrollbar.set)

# Run the tkinter event loop
window.mainloop()

Conclusion and Next Steps

Congratulations! You've created a simple yet functional Fibonacci sequence generator with a Tkinter GUI. This project demonstrates how Python can be used to create interactive applications.

For further learning, consider exploring more advanced Tkinter features, such as custom widgets, event handling, and integrating other Python libraries. Keep experimenting and expanding your skills to create even more complex and engaging applications.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺