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

Time:01-22

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

CodePudding user response:

The following code does the initialization, saving and loading of the checkbox value, althought the save function (basically took it from your example) causes an error if the checkbox is not selected when save is called. But as this is not part of the question I leave it to you to figure it out.


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

def init_db():
    conn = sqlite3.connect("GUI_state.db")
    c = conn.cursor()
    c.execute("create table table_checkbox (id integer, button_value integer, PRIMARY KEY('id' AUTOINCREMENT));")
    c.execute("insert into table_checkbox (button_value) values (0)")
    conn.commit()
    conn.close()


def save():
    value_Button1 = Checkbutton1_var.get()
    if Checkbutton1_var.get() == "":
        tkinter.messagebox.showerror("Select checkbox")
    else:
        conn = sqlite3.connect("GUI_state.db")
        c = conn.cursor()
        c.execute(f"UPDATE table_checkbox SET button_value = {value_Button1} WHERE id=1;")
        conn.commit()
        conn.close()
        messagebox.showinfo("Saved successfully")


def load():
    conn = sqlite3.connect("GUI_state.db")
    c = conn.cursor()
    button_val = c.execute("SELECT button_value FROM table_checkbox WHERE id=1;")
    button_val = tuple(button_val)[0]
    conn.close()
    return button_val


if __name__ == "__main__":
    if not os.path.exists("GUI_state.db"):
        init_db()
    root = tk.Tk()
    root.geometry("200x200")
    root.configure(bg='white')

    value = load()
    Checkbutton1_var = IntVar(value=value)

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

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

    root.mainloop()

CodePudding user response:

There are different things to keep in mind here, first of all is that you don't need to check for the value of Checkbutton1 and then only insert if it is "" because it will never be "", because it is an integer and never a string.

What you need here is to INSERT the state whatsoever if there is no records already in the table, and if there are records, then UPDATE the records, this is because you ID as PRIMARY KEY.

def save():
    value_Button1 = Checkbutton1.get()

    conn = sqlite3.connect("save.db")
    c = conn.cursor()
    c.execute('SELECT button1 FROM table_checkbox WHERE id=1')
    rec = c.fetchall()
    
    if rec:
        c.execute("UPDATE table_checkbox SET Button1=? WHERE id=1;", (value_Button1,))
    else:
        c.execute("INSERT INTO table_checkbox VALUES (1,?);", (value_Button1,))
    
    conn.commit()
    conn.close()

    messagebox.showinfo("Saved successfully","Saved successfully")

def load():
    conn = sqlite3.connect("save.db")
    c = conn.cursor()
    c.execute("SELECT button1 FROM table_checkbox")
    val = c.fetchone()[0]
    conn.close()

    Checkbutton1.set(val)

....
....
load()
root.mainloop()

You can also make it more user friendly and always check if the database is correctly made, if not, make the table again.

def create():
    conn = sqlite3.connect("save.db")
    c = conn.cursor()
    c.execute("""
    CREATE TABLE "table_checkbox" (
    "id"    INTEGER,
    "Button1"   INTEGER,
    PRIMARY KEY("id" AUTOINCREMENT)
);
    """)
    conn.close()

....
....
try:
    load()
except sqlite3.OperationalError:
    create()

root.mainloop()
  •  Tags:  
  • Related