In the following code I’ll show you how to calculate the factorial of a number using Python tkinter.
There are a Button, aEntry and a Label widgets in the GUI interface. When the button is clicked, “calculate” method runs. “calculate” method takes value form Entry widget and sends it to factorial method. After calculating the factorial of the number, the returned value is passed to the Label Widget.
Output:

Python Tkinter Code: Write a function that returns the factorial of a number python tkinter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import tkinter as tk from tkinter.colorchooser import * def factorial(n): # single line to find factorial return 1 if (n==1 or n==0) else n * factorial(n - 1); def calculate(): result=factorial(int(entryText.get())) info.config(text=result) mw = tk.Tk() mw.title('COLOR ME!!!') mw.geometry("200x200") mw.resizable(0, 0) entryText = tk.Entry(text=1, bg='white', fg='black') entryText.place(x = 50, y = 25, width=100, height=25) btn = tk.Button(text='Calculate', command=calculate) btn.place(x = 50, y = 75, width=100, height=25) info = tk.Label(text='result', bg='white', fg='black') info.place(x = 50, y = 125, width=100, height=25) mw.mainloop() |
This is a Python program that calculates the factorial of a number using the tkinter library for GUI.
The program starts by importing the tkinter library and the colorchooser module from tkinter. Then it defines a function called factorial() which takes an integer as an argument. Inside the function, it uses a ternary operator to check if the number is either 0 or 1, and if so, it returns 1. If not, it uses recursion to calculate the factorial by calling the function itself with the argument n-1 and multiplying it by n.
Then it defines another function called calculate() which is called when the user clicks the button. Inside the function, it calls the factorial function with the value entered by the user in the Entry widget, and assigns the result to a variable called “result”. Then it uses the config() method to update the text of the Label widget with the value of the “result” variable.
The program then creates a Tk() object and assigns it to a variable “mw”, and sets its title, size, and makes it non-resizable.
Then it creates an Entry widget to allow the user to enter a number, a Button widget with the text “Calculate” and the command to call the calculate() function, and a Label widget to display the result.
Finally, the program enters the main loop using the mainloop() method of the Tk() object, allowing the user to interact with the GUI and make calculations.
In summary, the program creates a simple GUI that allows the user to enter a number, calculates the factorial of that number using recursion, and displays the result using a Label widget.
How Can I get factorial for negative numbers?