Skip to content

Instantly share code, notes, and snippets.

@lgrachov
Created July 20, 2024 19:29
Show Gist options
  • Save lgrachov/155410b9aaa07b0638a1e8bbf82d62ef to your computer and use it in GitHub Desktop.
Save lgrachov/155410b9aaa07b0638a1e8bbf82d62ef to your computer and use it in GitHub Desktop.
Fibonacci GUI in Python
# fib.py
# Written by Lev Grachov
# Import Tkinter
# If you get module not installed, then run this command:
# For Linux: `sudo apt-get install python3-tk`
# For Windows: `pip install tk`
# For macOS: `brew install python-tk`
from tkinter.simpledialog import askinteger
from tkinter import *
from tkinter import messagebox
# Create the window
Win = Tk()
Win.geometry("300x130")
print("Window created")
# Make a function to ask for the input
def askInput():
Num = askinteger("Fibonacci", "Input the Integer")
print("The number inputted is " + str(Num))
fibonacciOf(Num)
# Fibonacci function
def fibonacciOf(n):
# Validate the value of n
if not (isinstance(n, int) and n >= 0):
raise ValueError(f'Positive integer number expected, got "{n}"')
# Handle the base cases
if n in {0, 1}:
return n
previous, fibNumber = 0, 1
for _ in range(2, n + 1):
# Compute the next Fibonacci number, remember the previous one
previous, fibNumber = fibNumber, previous + fibNumber
print("Fibonacci has been calculated")
Result.config(text = fibNumber)
print("Result label has been set to result")
return fibNumber
# Create the fibonacci button
But = Button(Win, text ="Fibonacci", command = askInput)
But.place(x=0,y=0)
print("Created button")
# Create the fibonacci result text box
Result = Label(Win, text="Result will be shown here")
Result.place(x=0,y=35)
print("Created textbox")
# Function to say that program window has been closed
try:
Win.mainloop()
except KeyboardInterrupt:
print("Program window has been closed. Stopping")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment