samedi 22 janvier 2022

How to view saved checkboxes? They are all displayed as selected, i cannot choose them individually (executable example)

I have code with executable example where the selection (0 or 1) of a combobox is saved in the database. If I open and close the window, the checkboxes are displayed as all selected, but I would like to display only those selected individually previously.

For example on 2 checkboxes, I would like to select only 1. Later when I close and open the window, I would like to see only 1 checkbox selected and not all. How can I solve?

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() 
Checkbutton3 = 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_Button1),))
    else:
        c.execute("INSERT INTO example VALUES (1,?,?);", ((value_Button1), (value_Button1),))
                    
        conn.commit()
        conn.close()
                
        messagebox.showinfo("Saved successfully","Saved successfully")



def load():
    conn = sqlite3.connect("...")
    c = conn.cursor()
    c.execute("SELECT button1 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