0

I'm writing a program that shows the Fibonacci sequence one number at a time. You are supposed to put in the number of numbers you want, and the numbers show one at a time. However, when I press the button, it just shows 1.

The first version of the code didn't work, because you would press the button and just get the final number. I tried (and failed) to fix it by adding "return fib" to the function, but that caused the current problem.

from time import sleep
from tkinter import *

def calc():
    a = 1
    b = 0
    c = 0
    w = texxt.get()
    num = int(w)
    for i in range(num):
        if a >= b:
            fib.set(str(a))
        elif b >= a:
            fib.set(str(b))
        else:
            fib.set("ERROR")
            break

        c = a + b

        if a >= b:
            b = c
        elif b >= a:
            a = c
        else:
            pass

        return fib

        sleep(1.2)


root = Tk()
fib = StringVar()
texxt = StringVar()
root.title("Fibonacci Calculator")

entry = Entry(root, textvariable = texxt)
entry.grid(row = 0, column = 0, sticky = 'nsew', padx = 3, pady = 3)

button = Button(root, text = "Start", command = calc)
button.grid(row = 1, column = 0, sticky='nsew', padx = 3, pady = 3)

label = Label(root, width = 10, textvariable = fib, relief = 'sunken')
label.grid(row = 0, column = 1, rowspan = 2, sticky = 'nsew')

root.mainloop()

I expect the next number to appear every 1.2 seconds, but I just get 1 and nothing else.

  • @ Zachary Berkowitz, your function `calc` returns `fib`, and since it's giving a return value, stops there. Try writing a procedure that changes the text in the label instead: that should be easier. – ofthegoats Jul 14 '19 at 16:15
  • Aside from that, you should be using the tkinter `after` method instead of `sleep`, which would otherwise cause problems for the GUI. Look [here](https://stackoverflow.com/questions/10393886/tkinter-and-time-sleep) – ofthegoats Jul 14 '19 at 16:23

0 Answers0