Facts App Using Tkinter module


In Python, we can use Tkinter module and randfacts module to create a Facts generator App. Tkinter is a Python GUI toolkit that is used to create graphical applications. You can create buttons, labels, text boxes, and other types of widgets using the Tkinter library. The randfacts is a Python module that generates random facts. In this article, we will implement a Fact App Generator GUI application using Tkinter and the randfacts module.

Creating the Facts Generator App

To create the facts generator app we first need to install the randfacts module using the Python package manager. To install the randfacts module type the following command on your terminal or command prompt.

pip install randfacts

To create the Facts Generator App we need to create some functions with the functionality to create widgets and generate facts using randfacts. The functions are described below −

  • Create_widgets − The create_widgets method creates a new Frame widget called facts_frame and packs it with some padding. This Frame will hold the generated facts. It also creates a Button widget called generate_fact_button that is linked to the generate_fact method.

  • Generate_fact − The generate_fact method generates a random fact using the randfacts.getFact function and creates a new Label widget called fact_label with the generated fact as its text. The fact_label widget is then packed into the facts_frame widget with some padding.

When the user clicks the “Generate_Fact” Button a new fact will be generated and displayed below the previous Fact in the fact_frame widget.

Example

import tkinter as tk
import randfacts

class FactsGeneratorApp(tk.Frame):
   def __init__(self, master=None):
      super().__init__(master)
      self.master = master
      self.master.title("Facts Generator App")
      self.create_widgets()

   def create_widgets(self):
      self.facts_frame = tk.Frame(self.master)
      self.facts_frame.pack(padx=20, pady=20)

      self.generate_fact_button = tk.Button(self.master, text="Generate Fact", command=self.generate_fact)
      self.generate_fact_button.pack(padx=20, pady=10)

   def generate_fact(self):
      fact = randfacts.getFact()
      fact_label = tk.Label(self.facts_frame, text=fact)
      fact_label.pack(pady=5)

root = tk.Tk()
app = FactsGeneratorApp(root)
app.mainloop()

Output

Conclusion

In this article, we discussed how we can use tkinter and randfacts modules to create a fact generator App in Python. The Tkinter module is used to create a GUI application and has several functions to make widgets. The randfacts module generates random facts and is used in the application to get Facts and show them on the widget screen.

Updated on: 10-Jul-2023

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements