2016-04-13 58 views
0

因此,我目前正在製作一個程序作爲BMI計算器,您可以在其中放入體重和身高,並將其輸出爲BMI並您的體重組,並可選擇將結果記錄到數據庫,然後您可以返回並查看以前的結果。我在嘗試從數據庫獲取信息並將其放入GUI以供用戶查看時遇到問題。將數據寫入數據庫是我已經出售的一個問題。我正在爲我的數據庫使用sqlite3,我的GUI使用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() 

任何幫助,這將非常感謝,我很堅持在這一點上! 謝謝,本

+0

你卡在哪裏?您已經設法寫入數據庫,因此您可以修改該命令以獲取值。你有tkinter運行,所以你能夠顯示值。問題是什麼? – tfv

+0

我不知道使用什麼命令來檢索和使用什麼來獲取一個表到GUI(我試過使用打印命令和標籤,但不起作用)我是新來的Tkinter和sqlite3,並不知道很多的命令的方式,只有我看到的教程 –

+0

看看這裏:sqlite教程:http://zetcode.com/db/sqlitepythontutorial/和這裏http:///stackoverflow.com/questions/9348264/does-tkinter-have-a-table-widget – tfv

回答

0

Tkinter自己不提供表格小部件,但您可以使用grid並在其中插入標籤。要從數據庫中獲取所有數據,只需執行查詢SELECT * FROM <Table>.fetchall()即可獲得包含雙字節的列表。這是您的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(),我們將從grid-方法中得到None,並且不能將該參考用於將來的目的。所以你需要糾正你的其他代碼。之後,我們從數據庫中提取所有數據,併爲每一行創建3個標籤。

+0

謝謝這麼多!像魅力一樣工作,也很好解釋! –

+0

沒問題。有趣的部分開始,如果你試圖刪除那些動態添加'標籤':) – VRage

相關問題