【发布时间】:2022-01-26 22:33:14
【问题描述】:
我有将其状态(活动或非活动)保存在数据库中的复选框。它们都分组在chk_lst = [] 中,然后保存在表的单个列中(所以只有id, checkbox)。这些已正确保存和加载。显然,如您所知,0 或 1 都被保存了。
接下来我想为每个复选框分配一个函数、一个类或任何其他类型的代码,以便我激活该复选框并执行分配的代码。因此,由于 sql 的条件,我调用了这样的某个复选框,但我不知道我是否做得对。
我担心由于我低估或认为不正确的事情,这段代码可能是错误的和/或将来会出现问题。我没有收到错误,但我不知道我是否正确运行它,考虑到代码和数据库将通过许多复选框实现
conn = sqlite3.connect('....')
cursor = conn.cursor()
cursor.execute('SELECT checkbox FROM table_example')
x = cursor.fetchone()
if checkbox[0] == "1": #THIS PART
code....
else:
None
为了确保答案的完整性,这是我用来将复选框保存在数据库中的代码。它运行良好且正常。问题不在这里
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')
chk_lst = []
#Checkbox
Checkbutton1 = IntVar()
Checkbutton2 = IntVar()
Button1 = Checkbutton(root, text = "Checkbox 1", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 1,
bg="white", foreground='black', activebackground="white")
Button1.place(x=10, y=36)
Button2 = Checkbutton(root, text = "Checkbox 2", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 1,
bg="white", foreground='black', activebackground="white")
Button2.place(x=10, y=66)
chk_lst.extend([Checkbutton1,Checkbutton2])
# Save Function
def save():
conn = sqlite3.connect(".....")
c = conn.cursor()
for idx,chk_btn in enumerate(chk_lst,start=1):
c.execute(f'SELECT checkbox FROM table_example WHERE id=?',(idx,))
rec = c.fetchall()
if rec:
c.execute("UPDATE table_example SET checkbox=? WHERE id=?;", (chk_btn.get(),idx))
else:
c.execute("INSERT INTO table_example VALUES (?,?);", (idx,chk_btn.get()))
conn.commit()
conn.close()
messagebox.showinfo("Saved successfully","Saved successfully")
# Load Function
def load():
conn = sqlite3.connect("....")
c = conn.cursor()
c.execute("SELECT * FROM table_example")
vals = c.fetchall()
for val,chk_btn in zip(vals,chk_lst):
chk_btn.set(val[1])
conn.close()
save = Button(root, text="save", bg='#b40909', foreground='white', command= save)
save.pack()
save.place(x=10, y=96)
load()
root.mainloop()
如上所述,数据库只是一个简单的表,有id列和复选框列
【问题讨论】:
-
"它们都分组在 chk_lst = []...": 不,没有复选框存储在那里。只有 tkinter 控制变量(
IntVar)在chk_lst。 -
请不要忘记花时间在这里发布答案的人:)
标签: python python-3.x sqlite tkinter checkbox