samedi 22 janvier 2022

How to activate the checkboxes saved in the database when I close and reopen the window?

I have a code where if you select/activate a checkbox, its value will be saved in the database as active or inactive (0 or 1). If you close and reopen the window, all active/selected checkboxes are shown even when they shouldn't.

enter image description here

PROBLEM: The problem lies in the upload function. It is wrong. The very logic of the code is wrong. It is useless to identify errors, it should be rewritten from scratch. I have no idea how to write it. For example, if I activate / select only one checkbox and save, then if I close and reopen the window, all checkboxes will be automatically activated.

WHAT DO I WANT? I would like that when I close and open the window, only the checkboxes that I have previously selected/activated are activated. For example, if I activate only Checkbox 1 and then I save, then subsequently when I close and open the window I would like to see only checkbox1 activated (not both).

import sqlite3
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import messagebox
import tkinter.messagebox

root = tk.Tk()
root.geometry("200x200")
root.configure(bg='white')

Checkbutton1 = IntVar() 
Checkbutton2 = IntVar() 
         
Button1 = Checkbutton(root, text = "Checkbutton1", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 1,
                            bg="white", foreground='black', activebackground="white")
Button1.place(x=10, y=26)
            
Button2 = Checkbutton(root, text = "Checkbutton2", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 1, 
                            bg="white", foreground='black', activebackground="white")
Button2.place(x=10, y=46)
                        
def save():
    value_Button1 = Checkbutton1.get()
    value_Button2 = Checkbutton2.get()

    conn = sqlite3.connect("...")
    c = conn.cursor()
    c.execute('SELECT button1 button2 FROM example WHERE id=1')
    rec = c.fetchall()

    if rec:
        c.execute("UPDATE example SET Button1=?, Button2=? WHERE id=1;", ((value_Button1), (value_Button2),))
    else:
        c.execute("INSERT INTO example VALUES (1,?,?);", ((value_Button1), (value_Button2),))
                    
        conn.commit()
        conn.close()
                
        messagebox.showinfo("Saved successfully","Saved successfully")
  
def load():
    conn = sqlite3.connect("...")
    c = conn.cursor()
    c.execute("SELECT * FROM example")
    val = c.fetchone()[0]
    conn.close()

    Checkbutton1.set(val)
    Checkbutton2.set(val)


load()
                    

save = Button(root, text="save", bg='#b40909', foreground='white', command= save)
save.pack()
save.place(x=10, y=90)

root.mainloop()

Example database

CREATE TABLE "example" (
    "id"    INTEGER,
    "Button1"   INTEGER,
    "Button2"   INTEGER,
    PRIMARY KEY("id" AUTOINCREMENT)
);



Aucun commentaire:

Enregistrer un commentaire