💻

Python TKinter GUI Development and APIs

Jun 22, 2024

Lecture on Python TKinter GUI Development and APIs

Introduction to TKinter

  • TKinter: Standard GUI library for Python
  • Creating Widgets: Buttons, text inputs, frames, etc.
  • Pack vs. Grid: Methods to arrange widgets

Creating a Simple GUI App

  • Importing TKinter: import tkinter as tk root = tk.Tk()
  • Creating Widgets: Examples include buttons, labels, entry fields button = tk.Button(root, text='Click Me') button.pack()
  • Event Loops: Main loop to run the app root.mainloop()

Working with Frames and Layouts

  • Frames: Contain and organize widgets frame = tk.Frame(root) frame.pack()
  • Grid Layout: Position widgets in rows and columns widget.grid(row=0, column=0)

Adding Functionality to Buttons

  • Command Option: Link buttons to functions button = tk.Button(root, text='Click Me', command=my_function)
  • Using Lambda for Passing Arguments: button = tk.Button(root, text='Click Me', command=lambda: my_function(arg))

Creating Input Forms

  • Entry Widgets: Text input fields entry = tk.Entry(root) entry.grid(row=0, column=0)
  • Labels for Inputs: Describe each entry field label = tk.Label(root, text='Name') label.grid(row=0, column=1)
  • Submitting Input: def submit(): name = entry.get() print(name)

Using Databases with TKinter

  • SQL Lite: Built-in database for Python import sqlite3 conn = sqlite3.connect('database.db') cursor = conn.cursor()
  • Creating Tables: cursor.execute("CREATE TABLE...?") conn.commit()
  • Inserting Records: Getting data from GUI and inserting into database cursor.execute("INSERT INTO...?") conn.commit()
  • Querying Data: Fetching and displaying data cursor.execute("SELECT ...?") records = cursor.fetchall()

Working with APIS

  • Request Library: To handle API calls import requests response = requests.get(api_url)
  • Parsing JSON Data import json data = json.loads(response.content)
  • Air Quality Example
    • Get API Key: From airnowapi.org
    • Handling Responses: Show results in GUI
    • Error Handling: Using try-except blocks
    try: api_response = requests.get(api_url).json() except Exception as e: print('Error:', e)
  • Dynamic Data Display on GUI

Adding Charts and Graphs

  • Libraries: numpy, matplotlib import numpy as np import matplotlib.pyplot as plt
  • Generating Sample Data data = np.random.normal(200000, 25000, 5000)
  • Displaying Graphs plt.hist(data, bins=50) plt.show()

Conclusion

  • Customization: More widgets, colors, fonts, etc.
  • Expanding: Adding more functionalities like updating, deleting records
  • Further Learning: Exploring in-depth topics such as data analysis, advanced widgets, etc.