vendredi 21 janvier 2022

Save two selected checkboxes, if i open and close the window (executable example)

I propose a small executable example of two checkboxes and a button. The goal is to save the selection / check of the combo boxes, in order to close the window and then reopen it to find the selected box. I would like to be able to choose whether to select one or all checkboxes, because I would like to avoid the problem of reloading all checkboxes when I reopen the window, but I want to reload only the selected ones.

I made the connection with Sql creating a table and the value is saved correctly. It is automatically saved 1 in the database, I don't know if it is correct. But if I close and reopen the window, the checkbox is no longer selected.

Can you show me what I can do with a reply? I'm new to Python, if you just leave a comment I might not understand. Thank you

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

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

Checkbutton1 = IntVar() 
Checkbutton2 = IntVar() 

#button 1            
Button1 = Checkbutton(root, text = "Checkbox 1", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 1,
                      bg="white", foreground='black', activebackground="white") #command=Button1_func)
Button1.place(x=10, y=36)

#button 2
Button2 = Checkbutton(root, text = "Checkbox 2", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 1,
                      bg="white", foreground='black', activebackground="white") #command=Button1_func)
Button2.place(x=10, y=56)
            

def save():
    value_Button1 = Checkbutton1.get()
    value_Button2 = Checkbutton2.get()
                
    if Checkbutton1.get() =="" or Checkbutton2.get() =="":
       tkinter.messagebox.showerror("Select checkbox")

    else:
        conn = sqlite3.connect("...")
        c = conn.cursor()

        c.execute("UPDATE table_checkbox SET Button1 =? Button=? WHERE id =1;", (value_Button1,), (value_Button2,))
        conn.commit()
        conn.close()
        messagebox.showinfo("Saved successfully")

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

root.mainloop()

Example Database

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



Aucun commentaire:

Enregistrer un commentaire