Hey everyone! I’ve been teaching myself Python and just built my first GUI program – a Fibonacci number generator using Tkinter. I know there’s room for improvement, so I’d love some feedback on my code structure and techniques.
Here’s my cleaned-up and modernized version (Python 3.x, with proper Tkinter usage):
import tkinter as tk
from tkinter import messagebox
def generate_fibonacci():
try:
n = int(entry.get())
except ValueError:
messagebox.showerror("Invalid Input", "Please enter an integer")
return
listbox.delete(0, tk.END)
a, b = 0, 1
for _ in range(n):
listbox.insert(tk.END, a)
a, b = b, a + b
root = tk.Tk()
root.title("Fibonacci Generator")
tk.Label(root, text="How many Fibonacci numbers?").pack(pady=5)
entry = tk.Entry(root)
entry.pack(pady=5)
tk.Button(root, text="Generate", command=generate_fibonacci).pack(pady=5)
listbox = tk.Listbox(root, width=50, height=10)
listbox.pack(pady=5)
root.mainloop()
I know my original version was pretty rough – no error handling, global variables everywhere, and the GUI wasn’t responsive. In this version, I’ve added input validation, used a function to encapsulate the logic, and kept the UI clean.
Some specific questions:
- Is it better to use a class-based approach for the app? I’ve seen examples with
class App(tk.Tk)but wasn’t sure if that’s overkill here. - Should I move the Fibonacci calculation to a separate module for reusability?
- Any Tkinter best practices I’m missing? I’ve heard about using
gridlayout instead ofpack– what’s your preference?
I’m also considering whether to let the user input starting values (not just from 0,1) – that could make it more flexible.
Thanks for taking a look! Any tips on improving my coding habits or the design would be awesome.
