我想添加一个按钮,让我在同一行查看笔记
我想创建一个小型桌面应用,既能查看我读过的书,也能查看我为它们写下的笔记。
我在使用SQLite3,数据库包含ID、标题、作者和笔记。但笔记比较长,最好把笔记存放在一个在点击按钮时就会打开的小窗口中。
如何将按钮放在书籍条目旁边,并且没有笔记时不显示它?我需要创建一个新函数吗?
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 view(self):
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()
i = 0
for i, ligne in enumerate(lignes):
self.label = ctk.CTkLabel(self, text= f"{ligne[0]} écrit par {ligne[1]}")
self.label.grid(row = i, column=1, padx=20, pady=20)
except Exception as e:
print(f'An error occured while creating the table : {e}')
class App(ctk.CTk):
def __init__(self):
super().__init__()
self.geometry("600x500")
self.title("Ajouter le livre")
# 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=300, height=200)
self.my_frame.grid(row=0, column=1, padx=20, pady=20)
# add methods to app
def button_click(self):
titre = self.entry.get()
auteur = self.entry2.get()
try:
with connection() as conn:
cursor = conn.cursor()
sql = "INSERT INTO Livres (titre_livre, auteur_livre) VALUES (?, ?);"
cursor.execute(sql, (titre, auteur))
except Exception as e:
print(f"An error occurred while inserting the book: {e}")
self.entry.delete(0, "end")
self.entry2.delete(0, "end")
app = App()
app.mainloop()
解决方案
你的SQL语句表明笔记存放在 ligne[2] 中,因此在笔记存在时使用 if/else 来显示按钮:
for i, ligne in enumerate(lignes):
# ... code ...
if ligne[2]:
self.button = ctk.CTkButton(self, text="Notes", command=lambda text=ligne[2]: self.show_notes(text))
self.button.grid(row=i, column=2)
现在你需要创建一个函数 show_notes(),它接收文本作为参数,并在一个单独的窗口中显示它。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。