python - 从数据库中获取数据并将其放入 GUI 中的表中

标签 python tkinter sqlite

所以,我目前正在制作一个充当 BMI 计算器的程序,您可以在其中输入您的体重和高度,它会将其输出为 BMI 和您的体重组,并且可以选择将您的结果记录到然后您可以返回并检查以前的结果的数据库。我在尝试从数据库获取信息并将其放入 GUI 中供用户查看时遇到问题。将数据写入数据库是我已经售出的一个问题。我使用 sqlite3 作为我的数据库,使用 Tkinter 作为我的 GUI。我怎样才能将此函数添加到我的代码中?这是我当前的代码

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 本身不提供表格小部件,但您可以使用 grid并在其中插入标签。要从数据库中获取所有数据,您只需执行查询 SELECT * FROM <Table>并与 .fetchall()你会得到一份带有双重的 list 。这是你的records类:

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

由于您关闭了与数据库的连接(这是一个错误,因为您无法计算另一个 BMI),我们需要再次打开它。之后,我们在网格布局中创建一个带有标签的“标题”。请注意,这里我们使用 grid在单独的一行上。原因是如果我们写 self.ourLabel = Label().grid()我们会得到 Nonegrid回来-方法并且不能将引用用于将来的目的。因此,您需要更正其他代码。之后,我们从数据库中获取所有数据并为每行创建 3 个标签。

关于python - 从数据库中获取数据并将其放入 GUI 中的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36590476/

相关文章:

Python pandas dataframe pivot 仅适用于 pivot_table() 但不适用于 set_index() 和 unstack()

python - CPython内存分配

python - tkinter:按下按钮添加新图像错误

python - StringVar.set ("...")在多个 tkinter 窗口中不起作用

java - Android Sqlite 和外键失败

python - SQLAlchemy:为什么附加到这种多对一关系会失败?

python - URL错误 : <urlopen error [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl. c:661)>

python - Canvas 文本更新 - Python3 Tkinter

java - 安卓插入语句

python - 使用execute插入多行