Python 从数据库获取数据并将其放入GUI中的表中
因此,我目前正在制作一个程序,作为BMI计算器,你可以输入你的体重和身高,它将输出为BMI和你的体重组,并可以选择将结果记录到数据库中,然后你可以返回并检查以前的结果。我在尝试从数据库获取信息并将其放入GUI以供用户查看时遇到问题。将数据写入数据库是我已经说过的一个问题。我正在对我的数据库使用sqlite3,对我的GUI使用Tkinter。我怎样才能把这个函数添加到我的代码中呢?这是我目前的代码Python 从数据库获取数据并将其放入GUI中的表中,python,tkinter,sqlite,Python,Tkinter,Sqlite,因此,我目前正在制作一个程序,作为BMI计算器,你可以输入你的体重和身高,它将输出为BMI和你的体重组,并可以选择将结果记录到数据库中,然后你可以返回并检查以前的结果。我在尝试从数据库获取信息并将其放入GUI以供用户查看时遇到问题。将数据写入数据库是我已经说过的一个问题。我正在对我的数据库使用sqlite3,对我的GUI使用Tkinter。我怎样才能把这个函数添加到我的代码中呢?这是我目前的代码 from Tkinter import * import sqlite3 import time i
from Tkinter import *
import sqlite3
import time
import datetime
conn = sqlite3.connect('bmidatabase.db')
c = conn.cursor()
class Welcome():
#This is the class defining the first welcoming window. This window is used to navigate between previous weights and the calculator.
def __init__(self,master):
#This is the GUI for the starting Menu area. Features three buttons for navigating towards the BMI Calculator, the Records where we have to store variables entered and the exit#
self.master=master
self.master.geometry('170x110+100+200')
self.master.title('Welcome!')
self.label1=Label(self.master,text='Welcome to the BMI Calculator',fg='red').grid(row=0,column=1)
self.button1=Button(self.master,text="BMI Calculator",fg='green',command=self.gotobmicalculator).grid(row=1,column=1)
self.button2=Button(self.master,text="Records",fg='blue',command=self.gotorecords).grid(row=2,column=1)
self.button3=Button(self.master,text="Exit",fg='red',command=self.exit).grid(row=3,column=1)
def exit(self):
#Exit protocol for the exit button. This part is completely done.#
self.master.destroy()
def gotobmicalculator(self):
#This is the BMI Calculator GUI#
root2=Toplevel(self.master)
myGUI=bmicalculator(root2)
def gotorecords(self):
#This is where the previous records of BMI will be kept, hasn't been put in yet#
root2=Toplevel(self.master)
mygui=records(root2)
class bmicalculator():
#class created for the bmi calculator GUI and processing the numbers (pain in the ass to make)#
def __init__(self,master):
c.execute('CREATE TABLE IF NOT EXISTS BMIStorage(timestamp TEXT,bodymassindex REAL,weightclass TEXT)')
self.heightcm=DoubleVar()
self.weightkg=DoubleVar()
self.master=master
self.master.geometry('250x200+100+200')
self.master.title('BMI Calculator')
self.label2=Label(self.master,text='Welcome to the BMI Calculator',fg='red').grid(row=0,column=0)
self.label2=Label(self.master,text='Please enter your height in centimetres',fg='black').grid(row=3,column=0)
self.label2=Label(self.master,text='Please enter your weight in kilograms',fg='black').grid(row=4,column=0)
self.myheight=Entry(self.master,textvariable=self.heightcm).grid(row=3,column=1)
self.myweight=Entry(self.master,textvariable=self.weightkg).grid(row=4,column=1)
self.button4=Button(self.master,text="Calculate BMI",fg='red',command=self.bmicalculation).grid(row=7,column=0)
self.button5=Button(self.master,text="Exit",fg='red',command=self.exit).grid(row=9,column=0)
def bmicalculation(self):
bmiheight=self.heightcm.get()
print bmiheight
bmiweight=self.weightkg.get()
bmi= float((bmiweight)/((bmiheight / 100)**2))
self.bmi = bmi
print bmi
self.label1=Label(self.master,text='Your BMI is %.2f' % bmi).grid(row=5,column=0)
if bmi <= 18.5:
self.label2=Label(self.master,text='This places you in the underweight group.',fg='blue').grid(row=6,column=0)
totalindex = 'underweight'
self.totalindex = totalindex
elif bmi >18.5 and bmi <25:
self.label3=Label(self.master,text='This places you in the healthy weight group.',fg='green').grid(row=6,column=0)
totalindex = 'healthy'
self.totalindex = totalindex
elif bmi >= 25 and bmi < 30:
self.label4=Label(self.master,text='This places you in the overweight group.',fg='orange').grid(row=6,column=0)
totalindex = 'overweight'
self.totalindex = totalindex
elif bmi >=30:
self.label5=Label(self.master,text='This places you in the obese group.',fg='red').grid(row=6,column=0)
totalindex = 'obese'
self.totalindex = totalindex
if bmi >0 and bmi <999999999999999999999:
self.button6=Button(self.master,text="Store Data",fg='red',command=self.dynamic_data_entry).grid(row=8,column=0)
def dynamic_data_entry(self):
global dynamic_data_entry
#this is what adds the data to the database. Bmi has to be changed to the value of bmi and weightclass has to be change to the weightclass
timestamp = str(datetime.datetime.now().date())
bodymassindex = self.bmi
weightclass = self.totalindex
c.execute("INSERT INTO BMIStorage (timestamp, bodymassindex, weightclass) VALUES (?, ?, ?)",(timestamp, bodymassindex, weightclass))
conn.commit()
self.writetodatabase()
def writetodatabase(self):
for i in range(1):
time.sleep(1)
c.close()
conn.close()
def exit(self):
#Exit protocol for the exit button. This part is completely done.#
self.master.destroy()
class records():
#class created to see records that have been previously inputted#
def __init__(self,master):
self.master=master
self.master.geometry('250x200+100+200')
self.master.title('Records')
def main():
root=Tk()
myGUIWelcome=Welcome(root)
root.mainloop()
if __name__ == '__main__':
main()
从Tkinter导入*
导入sqlite3
导入时间
导入日期时间
conn=sqlite3.connect('bmidatabase.db')
c=连接光标()
类Welcome():
#这是定义第一个欢迎窗口的类。此窗口用于在以前的权重和计算器之间导航。
定义初始(自我,主):
#这是开始菜单区域的GUI。功能有三个按钮,用于导航到BMI计算器,记录我们必须在其中存储输入的变量和退出#
self.master=master
自主几何(“170x110+100+200”)
self.master.title('欢迎!')
self.label1=Label(self.master,text='欢迎使用BMI计算器',fg='red').grid(行=0,列=1)
self.button1=按钮(self.master,text=“BMI Calculator”,fg='green',command=self.gotobmicalculator).grid(行=1,列=1)
self.button2=按钮(self.master,text=“Records”,fg='blue',command=self.gotorecords).grid(行=2,列=1)
self.button3=按钮(self.master,text=“Exit”,fg='red',command=self.Exit).grid(行=3,列=1)
def出口(自):
#退出按钮的退出协议。这部分已经完成了#
self.master.destroy()
def GOTOBMIC计算器(自身):
#这是BMI计算器GUI#
root2=顶级(self.master)
myGUI=bmicalculator(root2)
def gotorecords(自):
#这是以前的BMI记录保存的地方,还没有放进去#
root2=顶级(self.master)
mygui=记录(root2)
类计算器():
#为bmi计算器GUI创建的类,并处理这些数字(让人头疼)#
定义初始(自我,主):
c、 执行('CREATE TABLE IF NOT existence bmi storage(时间戳文本、bodymassindex REAL、weightclass文本)')
self.heightcm=DoubleVar()
self.weightkg=DoubleVar()
self.master=master
自主几何(“250x200+100+200”)
self.master.title(“BMI计算器”)
self.label2=Label(self.master,text='欢迎使用BMI计算器',fg='red').grid(行=0,列=0)
self.label2=Label(self.master,text='请以厘米为单位输入您的身高',fg='black').grid(行=3,列=0)
self.label2=Label(self.master,text='请以千克为单位输入您的体重',fg='black').grid(行=4,列=0)
self.myheight=Entry(self.master,textvariable=self.heightcm).grid(行=3,列=1)
self.myweight=Entry(self.master,textvariable=self.weightkg).grid(行=4,列=1)
self.button4=按钮(self.master,text=“计算体重指数”,fg='red',command=self.bmiculation).grid(行=7,列=0)
self.button5=按钮(self.master,text=“Exit”,fg='red',command=self.Exit).grid(行=9,列=0)
def BMI计算(自):
bmiheight=self.heightcm.get()
打印高度
bmiweight=self.weightkg.get()
体重指数=浮动((体重指数)/(身高指数/100)**2))
self.bmi=bmi
打印体重指数
self.label1=Label(self.master,text=)您的体重指数是%.2f'%BMI'。网格(行=5,列=0)
如果bmi为18.5且bmi=25且bmi<30:
self.label4=Label(self.master,text='This places you in the超重组',fg='orange').grid(行=6,列=0)
totalindex=‘超重’
self.totalindex=totalindex
如果体重指数>=30:
self.label5=Label(self.master,text='This places you in the footbality group',fg='red').grid(行=6,列=0)
totalindex=‘肥胖’
self.totalindex=totalindex
如果bmi>0和bmiTkinter本身不提供表小部件,但您可以使用grid
并在其中插入标签。要从数据库中获取所有数据,只需执行一个查询SELECT*from
,并使用。fetchall()
即可获得一个带有duble的列表。这是您的记录
课程:
class records():
#class created to see records that have been previously inputted#
def __init__(self,master):
self.master=master
self.master.geometry('250x200+100+200')
self.master.title('Records')
self.connection = sqlite3.connect('bmidatabase.db')
self.cur = self.connection.cursor()
self.dateLabel = Label(self.master, text="Date", width=10)
self.dateLabel.grid(row=0, column=0)
self.BMILabel = Label(self.master, text="BMI", width=10)
self.BMILabel.grid(row=0, column=1)
self.stateLabel = Label(self.master, text="Status", width=10)
self.stateLabel.grid(row=0, column=2)
self.showallrecords()
def showallrecords(self):
data = self.readfromdatabase()
for index, dat in enumerate(data):
Label(self.master, text=dat[0]).grid(row=index+1, column=0)
Label(self.master, text=dat[1]).grid(row=index+1, column=1)
Label(self.master, text=dat[2]).grid(row=index+1, column=2)
def readfromdatabase(self):
self.cur.execute("SELECT * FROM BMIStorage")
return self.cur.fetchall()
由于您已经关闭了与数据库的连接(这是一个bug,因为您无法计算另一个BMI),我们需要再次打开它。然后,我们在网格布局中创建一个带有标签的“标题”。请注意,我们在单独的行上使用网格
。这样做的原因是,如果我们编写self.ourLabel=Label().grid()
,我们将从grid
-方法返回None
,并且不能将引用用于将来的用途。因此,您需要更正其他代码。之后,我们从数据库中获取所有数据,并为每行创建3个标签。您被困在哪里?您已成功写入数据库,因此可以修改该命令以获取返回的值。tkinter正在运行,因此可以显示值。问题出在哪里?我不知道使用什么命令来检索,也不知道使用什么命令将表放入GUI(我尝试过使用print命令和labels,但不起作用)我对Tkinter和sqlite3都不熟悉,对命令知之甚少,只有我在教程中看到的,请看这里:sqlite教程:这里非常感谢!工作起来很有魅力,而且解释得也很好!没问题。如果您试图删除那些动态添加的Label
s:),那么有趣的部分就开始了