将多个选择功能应用于复选框(它们从数据库中保存和加载)

Apply multiple selection functions to checkboxes (they are saved and loaded from the database)

我有一个可执行代码,可以在数据库中保存和加载选中或未选中的复选框。这工作正常。

每个复选框都有我在 中由友善的用户 acw1668 谈到的功能(阅读解决方案)。我想将解决方案应用于我的这个问题的代码。您可以从解决了基于 True 或 False 的多选复选框问题的用户的响应代码中得到提示。我想将 link 的另一个问题的解决方案应用于我在这个新问题中报告的我的完整代码,因为此外这个新问题的代码还具有复选框的保存和加载。

我想要什么?我希望当您单击“打印”按钮时,根据复选框的多重选择及其功能在文本框中打印“确定”。如果基于函数的复选框 returns False,则它不会打印“ok”。如果基于函数的复选框 returns True,则它会在文本框中打印“ok”。如果3个checkbox都被选中,则不会打印任何内容,因为其中有checkbox2抵制False。例如,如果选中的复选框 1 和 3 为 True,则打印“ok”。

我要添加的代码(link 的另一个问题的代码)的目的是识别选中的多个复选框的多个是:

def clicked(flag, func):
    if flag:
        funclist.add(func)
    else:
        funclist.remove(func)

funclist = set()

def aaa():
    # if need to clear the text box, uncomment below line
    #textbox.delete("1.0", "end")
    if funclist and all(func() for func in funclist):
        textbox.insert("end", "Ok")

我保存和加载复选框(包括 GUI)的代码是:

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("400x500")
root.configure(bg='white')

chk_lst = []

#CHECKBOX
Checkbutton1 = IntVar()
Checkbutton2 = IntVar()
Checkbutton3 = IntVar() 

#CHECKBOX FUNCTION

def Button1_func():
    if 5 + 3 == 8:
        return True
    else:
        return False

def Button2_func():
    if 5 + 3 == 7:
        return True
    else:
        return False

def Button3_func():
    if 5 + 3 == 8:
        return True
    else:
        return False
    
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=60)

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

Button3 = Checkbutton(root, text = "Checkbox 2", variable = Checkbutton3, onvalue = 1, offvalue = 0, height = 1,
                      bg="white", foreground='black', activebackground="white", command=Button3_func)
Button3.place(x=10, y=140)

chk_lst.extend([Checkbutton1,Checkbutton2,Checkbutton3])


#SAVE IN DATABASE
def save():
    conn = sqlite3.connect("value.db")
    c = conn.cursor()
    
    for idx,chk_btn in enumerate(chk_lst,start=1):
        c.execute(f'SELECT button1 FROM table1 WHERE id=?',(idx,))
        rec = c.fetchall()

        if rec:
            c.execute("UPDATE table1 SET Button1=? WHERE id=?;", (chk_btn.get(),idx))
        else:
            c.execute("INSERT INTO table1 VALUES (?,?,?);", (idx,chk_btn.get()))
        
    conn.commit()
    conn.close()

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


#LOAD WHEN OPEN WINDOWS
def load():
    conn = sqlite3.connect("value.db")
    c = conn.cursor()
    c.execute("SELECT * FROM table1")
    vals = c.fetchall()
    
    for val,chk_btn in zip(vals,chk_lst):
        chk_btn.set(val[1])
    
    conn.close()


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

#PRINT BUTTON
button = tk.Button(root, text="Print", command= lambda: [aaa()])
button.place(x=100, y=10)

#TEXTOBOX
textbox = tk.Text(root, width=33, height=10, font=('helvetic', 12))
textbox.place(x=10, y=220)

load()

root.mainloop()

简单数据库:

CREATE TABLE "table1" (
    "id"    INTEGER,
    "Button1"   TEXT,
    PRIMARY KEY("id" AUTOINCREMENT)
);

您还需要另一个列表来存储函数引用:

chk_lst = []
fn_list = []

然后更新为 chk_list:

chk_lst.extend([Checkbutton1, Checkbutton2, Checkbutton3])
fn_lst.extend([Button1_func, Button2_func, Button3_func])

load() 中,您可以根据从数据库中检索到的数据更新 set funclist

def load():
    conn = sqlite3.connect('value.db')
    c = conn.cursor()
    c.execute('SELECT * FROM table1 ORDER BY id')
    vals = c.fetchall()

    for val, chk_btn, func in zip(vals, chk_lst, fn_lst):
        chk_btn.set(val[1])
        if val[1] == '1':
            funclist.add(func)

    conn.close()

基于您的代码的完整示例:

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


root = tk.Tk()
root.geometry("600x600")
root.configure(bg='white')

chk_lst = []
fn_lst = []
funclist = set()

Checkbutton1 = tk.IntVar()
Checkbutton2 = tk.IntVar()
Checkbutton3 = tk.IntVar()

#CHECKBOX'S FUNCTIONS
def Button1_func():
    if 5 + 3 == 8:
        return True
    else:
        return False

def Button2_func():
    if 5 + 3 == 7:
        return True
    else:
        return False

def Button3_func():
    if 5 + 3 == 8:
        return True
    else:
        return False

def clicked(flag, func):
    if flag:
        funclist.add(func)
    else:
        funclist.remove(func)


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

Button2 = tk.Checkbutton(root, text = "Checkbox 2", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 1,
                         bg="white", foreground='black', activebackground="white",
                         command=lambda: clicked(Checkbutton2.get(), Button2_func))
Button2.place(x=10, y=66)

Button3 = tk.Checkbutton(root, text = "Checkbox 3", variable = Checkbutton3, onvalue = 1, offvalue = 0, height = 1,
                         bg="white", foreground='black', activebackground="white",
                         command=lambda: clicked(Checkbutton3.get(), Button3_func))
Button3.place(x=10, y=146)

chk_lst.extend([Checkbutton1, Checkbutton2, Checkbutton3])
fn_lst.extend([Button1_func, Button2_func, Button3_func])


#SAVE IN DATABASE
def save():
    conn = sqlite3.connect('value.db')
    c = conn.cursor()

    for idx, chk_btn in enumerate(chk_lst, start=1):
        try:
            c.execute('INSERT INTO table1 VALUES (?, ?)', (idx, chk_btn.get()))
        except sqlite3.IntegrityError:
            c.execute('UPDATE table1 SET Button1 = ? WHERE id = ?', (chk_btn.get(), idx))

    conn.commit()
    conn.close()

    messagebox.showinfo('SAVE', 'Saved successfully')


#LOAD WHEN OPEN WINDOWS
def load():
    conn = sqlite3.connect('value.db')
    c = conn.cursor()
    c.execute('SELECT * FROM table1 ORDER BY id')
    vals = c.fetchall()

    for val, chk_btn, func in zip(vals, chk_lst, fn_lst):
        chk_btn.set(val[1])
        if val[1] == '1':
            funclist.add(func)

    conn.close()


#BUTTON FUNCTION
def aaa():
    # if need to clear the text box, uncomment below line
    #textbox.delete("1.0", "end")
    if funclist and all(func() for func in funclist):
        textbox.insert("end", "Ok")


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

#TEXTOBOX
textbox = tk.Text(root, width=33, height=10, font=('helvetic', 12))
textbox.place(x=10, y=220)

#PRINT BUTTON
button = tk.Button(root, text="Print", command= lambda: [aaa()])
button.place(x=100, y=10)

load()

root.mainloop()