You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于CustomTkinter与SQLite3的读书笔记应用:笔记查看按钮的条件显示与弹窗功能实现咨询

Solution for Your Book Notes Desktop App

Hey Hugo, let's work through your three questions and adjust your code to implement the note-viewing feature perfectly:


1. Placing the Note Button on the Same Row as Book Entries

To get the button aligned with each book's label, just use the same row value for both widgets in the grid layout. Assign the book label to column 1 and the button to column 2—this keeps them side-by-side horizontally.

2. Hiding the Button When There's No Note

Add a simple check: only create the button if prise_de_note (the third value in each ligne tuple) is not empty or None. Skip button creation entirely for books without notes to keep the UI clean.

3. Do You Need New Functions?

Absolutely! You'll need two key new functions:

  • A function to pop up a window displaying the note content (handles long notes with a scrollable view)
  • A function to refresh the book list after adding a new book (so your UI updates automatically without restarting the app)

Updated Full Code

Here's your revised code with all these features implemented:

import os
import sqlite3
import customtkinter as ctk

dossier_actuel = os.path.dirname(os.path.abspath(__file__))
chemin_base_donnees = os.path.join(dossier_actuel, "bibliotheque.db")

def connection():
    return sqlite3.connect(chemin_base_donnees)

def crea_biblio():
    try:
        with connection() as conn:
            cursor = conn.cursor()
            sql = '''CREATE TABLE IF NOT EXISTS Livres (
                    id_livre INTEGER PRIMARY KEY AUTOINCREMENT,
                    titre_livre TEXT,
                    auteur_livre TEXT,
                    prise_de_note TEXT );'''
            cursor.execute(sql)
            conn.commit()
    except Exception as e:
        print(f"An error occured while creating the table : {e}")

class MyFrame(ctk.CTkScrollableFrame):
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)
        self.view()

    def show_note_window(self, note_content):
        # Create a pop-up window to display the note
        note_window = ctk.CTkToplevel(self)
        note_window.title("Notes du livre")
        note_window.geometry("400x300")
        
        # Add a scrollable text box for long notes
        note_text = ctk.CTkTextbox(note_window, wrap="word")
        note_text.pack(padx=15, pady=15, fill="both", expand=True)
        note_text.insert("1.0", note_content)
        note_text.configure(state="disabled")  # Make text read-only

    def view(self):
        # Clear existing widgets before reloading (prevents duplicate entries)
        for widget in self.winfo_children():
            widget.destroy()
            
        try:
            with connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT titre_livre, auteur_livre, prise_de_note FROM Livres ORDER BY id_livre")
                lignes = cursor.fetchall()
                for i, ligne in enumerate(lignes):
                    titre, auteur, note = ligne
                    # Create book label
                    book_label = ctk.CTkLabel(self, text=f"{titre} écrit par {auteur}")
                    book_label.grid(row=i, column=1, padx=20, pady=20, sticky="w")
                    
                    # Only create button if note exists and isn't empty
                    if note and note.strip():
                        note_button = ctk.CTkButton(self, text="Voir notes", 
                                                   command=lambda n=note: self.show_note_window(n))
                        note_button.grid(row=i, column=2, padx=10, pady=20)
        except Exception as e:
            print(f'An error occured while loading books : {e}')

class App(ctk.CTk):
    def __init__(self):
        super().__init__()
        self.geometry("800x500")  # Widen window to fit buttons
        self.title("Ma Bibliothèque avec Notes")

        # Add widgets to app
        self.button = ctk.CTkButton(self, text="Ajouter le livre", command=self.button_click)
        self.button.grid(row=2, column=0, padx=20, pady=10)

        self.entry = ctk.CTkEntry(self, placeholder_text="Titre du livre")
        self.entry.grid(row=0, column=0, padx=20, pady=10)

        self.entry2 = ctk.CTkEntry(self, placeholder_text="Auteur")
        self.entry2.grid(row=1, column=0, padx=20, pady=10)

        self.my_frame = MyFrame(master=self, width=500, height=400)
        self.my_frame.grid(row=0, column=1, rowspan=3, padx=20, pady=20)

    # Add methods to app
    def button_click(self):
        titre = self.entry.get().strip()
        auteur = self.entry2.get().strip()
        if not titre or not auteur:
            print("Veuillez entrer un titre et un auteur valides !")
            return
            
        try:
            with connection() as conn:
                cursor = conn.cursor()
                sql = "INSERT INTO Livres (titre_livre, auteur_livre) VALUES (?, ?);"
                cursor.execute(sql, (titre, auteur))
                conn.commit()
                print(f"Livre '{titre}' ajouté avec succès !")
        except Exception as e:
            print(f"An error occurred while inserting the book: {e}")
            
        # Clear entries and refresh the book list
        self.entry.delete(0, "end")
        self.entry2.delete(0, "end")
        self.my_frame.view()  # Refresh the frame to show new book

# Initialize database and run app
crea_biblio()
app = App()
app.mainloop()

Key Improvements Explained

  • Same-row button placement: Each book label and button share the same row=i value in grid, with columns 1 and 2 for clean alignment.
  • Conditional button display: The if note and note.strip() check ensures buttons only appear for books with non-empty, meaningful notes.
  • Pop-up note window: The show_note_window function creates a scrollable read-only text box to comfortably display long notes.
  • Auto-refreshing UI: After adding a book, self.my_frame.view() reloads the list so new entries show up immediately.
  • Input validation: We added a check to prevent empty book titles/authors from being added to the database.

内容的提问来源于stack exchange,提问作者Hugo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 09:22:34