Build a Simple Blog Application with Python and CustomTkinter
Demo :
Click Video πππ
Code :
Libraries Required: cmd => pip install customtkinter
import sqlite3
from tkinter import *
from tkinter import messagebox
import customtkinter as ctk
# Database setup
conn = sqlite3.connect('blog.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
''')
conn.commit()
# Functions
def create_post():
title = title_entry.get()
content = content_entry.get("1.0", "end-1c")
if title and content:
cursor.execute("INSERT INTO posts (title, content) VALUES (?, ?)", (title, content))
conn.commit()
messagebox.showinfo("Success", "Post created successfully!")
title_entry.delete(0, "end")
content_entry.delete("1.0", "end")
display_posts()
else:
messagebox.showwarning("Input Error", "Please provide both title and content!")
def display_posts():
cursor.execute("SELECT * FROM posts ORDER BY created_at DESC")
posts = cursor.fetchall()
posts_listbox.delete(0, "end")
for post in posts:
posts_listbox.insert("end", f"{post[1]} - {post[3]}")
# GUI setup using CustomTkinter for modern design
ctk.set_appearance_mode("Dark") # Dark mode theme
ctk.set_default_color_theme("blue") # Blue color theme
root = ctk.CTk() # Use CustomTkinter's root instead of Tk()
root.title("Simple Blog Application")
root.geometry("600x600")
# Title Label
title_label = ctk.CTkLabel(root, text="Create a New Post", font=("Arial", 18), text_color="white")
title_label.pack(pady=20)
# Title Entry
title_entry = ctk.CTkEntry(root, width=500, height=40)
title_entry.pack(pady=10)
# Content Label
content_label = ctk.CTkLabel(root, text="Post Content", font=("Arial", 14), text_color="white")
content_label.pack(pady=10)
# Content Textbox
content_entry = ctk.CTkTextbox(root, width=500, height=150)
content_entry.pack(pady=10)
# Create Post Button
create_button = ctk.CTkButton(root, text="Create Post", command=create_post, width=200, height=40)
create_button.pack(pady=20)
# Posts Listbox (display previous posts)
posts_label = ctk.CTkLabel(root, text="Previous Posts", font=("Arial", 16), text_color="white")
posts_label.pack(pady=10)
posts_listbox = ctk.CTkTextbox(root, width=500, height=150, state="disabled")
posts_listbox.pack(pady=10)
# Display posts on startup
display_posts()
# Run the GUI
root.mainloop()
# Close the database connection
conn.close()
Comments
Post a Comment