jeudi 20 janvier 2022

Save checkbox selection, if i open and close the window (executable example)

I propose a small executable example of a checkbox and a button. The goal is to save the combobox selection/check, with the purpose to close the window and then re-open it to find the selected checkbox again.

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() 
            
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)
            

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

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

        c.execute("UPDATE table_checkbox SET Button1 =? WHERE id =1;", (value_Button1,))
        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,
    PRIMARY KEY("id" AUTOINCREMENT)
);



Aucun commentaire:

Enregistrer un commentaire