Search code examples
pythontkintercalculatorfactorial

Python Factorial Calculator Error?


So, I starting to learning Tkinter in Python, (just starting to learn Python, for that matter) and decided to try and create a factorial calculator using Tkinter. I'm not going for anything too fancy and here is what I've come up with:

from Tkinter import *
import tkMessageBox

def calculate():
    number = inputNumber.get()
    inputNumber.delete(0, END)
    product = 1
    for i in range(number):
        product = product * (i+1)
    inputNumber.insert(product)

cal = Tk()
cal.title("Factorial Calculator")
cal.geometry('450x300+200+200')

factorialNumber = IntVar()
inputNumber = Entry(cal, textvariable=factorialNumber)
inputNumber.pack()

enterButton= Button(cal, text="CALCULATE!", width=20,command=calculate)
enterButton.pack(side='bottom',padx=15,pady=15)

cal.mainloop()

So I ran this, and when I hit the "CALCULATE!" button, it spits out this error:

Traceback (most recent call last):
File "C:\Python27\Lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Users\Wesley Yu\Desktop\New folder (4)\module1.py", line 8, in calculate
for i in range(number):
TypeError: range() integer end argument expected, got str.

I've already tried fixing it, but to no avail. What should I do?

Sorry if this is very basic, still learning :)


Solution

  • Entries result in strings. Pass it to the int() constructor first.

    >>> int('42')
    42