2016-02-27 64 views
2

我已經使用Tkinter來創建單選按鈕,通過它我想在單擊提交按鈕後在數據庫中增加一個單選按鈕。如何連接到python的gui中的mysql數據庫

最重要的是我想連接到MySQL數據庫,但我不知道要在腳本中添加什麼。

from Tkinter import * 
root= Tk() 
frm=Frame(root,relief=RAISED,borderwidth=5,bg="green") 
Label(frm,text= "PLEASE SELECT CANDIDATE\n OF YOUR CHOICE\n\n\n\n",bg="green").pack() 
var = IntVar() 
for text, value in [('YOWERI KAGUTA MUSEVENI', 1), ('KIIZA BESIGYE', 2), ('AMAAMA JOHN MBABAZI ', 3), 
('KARUNGI SHARON', 4), ('BYAMUKAMA OSCAR', 5), 
('MATILDA MOREEN', 6), ('DUNCANS', 7)]: 

Radiobutton(frm, text=text, value=value, variable=var,padx=18,bg="green" 
).pack(anchor=E, fill=X, padx=18) 
var.set(0) 
frm.pack(pady=10) 
btn=Button(frm,text='submit',fg="black",bg="yellow") 
btn.pack(anchor=E) 
root.title("movie chooser") 

root.mainloop() 
+0

這些按鈕項與您的數據庫之間的關係是什麼?您是否嘗試執行插入,刪除,顯示或...? –

+0

只要選擇了raibutton並按下提交按鈕,就更新表格。更新按1遞增。 –

回答

2

我將逐步指導您解決您的問題。我假設你已經在Ubuntu上安裝了MySQL服務器。

無論您是使用Tkinter還是其他一些GUI軟件包,實現目標的方法都是一樣的。

我需要使用哪些工具?

首先,您將需要安裝一個Python數據庫接口,該接口將允許您使用Python與MySQL服務器進行通信。這裏是詳盡的list of Python MySQL databse interfaces

哪一個更好安裝?我更願意談談我自己使用的其中的兩種:MySQLdbMySQL connector

MySQLdb是一個C庫,它比MySQL連接器更快,它是一個純Python庫。爲了便攜性,最好選擇後者。爲了速度,你需要選擇第一個。請注意,Django使用MySQLdb。這也是我將在以下使用的我最喜歡的數據庫接口。你可以在這兩個接口here之間找到一個很好的比較。

如何在Ubuntu 14.04.3 LTS上安裝MySQLdb?

安裝MySQLdb的常用方法是使用pip,如here所述。但對於Ubuntu的,通過我的親身經歷,我更願意安裝這樣說:

  • 安裝所需的依賴:sudo apt-get install build-essential python-dev libmysqlclient-dev
  • 安裝MySQL DATABSE接口本身:sudo apt-get install python-mysqldb

現在,你應該能夠將其導入: >>> import MySQLdb

接口設計

首先,我們會要求用戶輸入自己的憑據MySQL服務器:

enter image description here

如果證書不正確,窗口仍會在那裏提示自己,除非用戶存在該應用程序。

如果憑據是正確的,然後用戶可以保存/他最喜歡的開始,通過類似於你設計了一個新的窗口添加到數據庫:

enter image description here

實現應用程序:

1。數據庫設計:

我選擇了最簡單的一個,正好滿足了這一燃眉之急:

mysql> CREATE DATABASE begueradj;

現在是時候建立我們在其中保存自己喜歡的明星表。它將包含他們的名字starname和自動遞增的主鍵id

mysql> USE begueradj; 
mysql> CREATE TABLE mystars(id INT(2) NOT NULL AUTO_INCREMENT, 
          starname VARCHAR(40) NOT NULL, 
          PRIMARY KEY(id) 
          ); 

2.首先實現接口:

由第一張截圖所示的界面是由initialize_user_interface()函數創建:

def initialize_user_interface(self): 
     """Draw a user interface allowing the user to type 
     MySQL server credentials 
     """ 
     self.parent.title("DB operations")  
     self.parent.grid_rowconfigure(0,weight=1) 
     self.parent.grid_columnconfigure(0,weight=1) 
     self.parent.config(background="lavender") 

     self.label_user=Tkinter.Label(self.parent,text="DB User: ",anchor=Tkinter.W,background="dark slate gray",foreground="white", font="Helvetica 8 bold") 
     self.label_password=Tkinter.Label(self.parent,text="DB Password:", anchor=Tkinter.W,background="dark slate gray",foreground="white", font="Helvetica 8 bold") 

     self.label_user.grid(row=0,column=0,sticky=Tkinter.E+Tkinter.W) 
     self.label_password.grid(row=1,column=0, sticky=Tkinter.E+Tkinter.W) 

     self.dbuser=Tkinter.Entry(self.parent) 
     self.dbpassword=Tkinter.Entry(self.parent,show="*") 

     self.dbuser.grid(row=0,column=1,sticky=Tkinter.E+Tkinter.W) 
     self.dbpassword.grid(row=1,column=1,sticky=Tkinter.E+Tkinter.W) 

     self.connectb=Tkinter.Button(self.parent,text="Log in",font="Helvetica 10 bold",command=self.dbconnexion) 
     self.cancelb=Tkinter.Button(self.parent,text="Cancel",command=self.parent.quit,font="Helvetica 10 bold") 

     self.connectb.grid(row=2,column=1,sticky=Tkinter.W) 
     self.cancelb.grid(row=2,column=2) 

主要是,我將函數dbconnexion()綁定到登錄按鈕self.connectb

def dbconnexion(self): 
     """ Pop up a new window if the credentials are the right ones 
     """  
     if self.dbuser.get()=="beueradj" and self.dbpassword.get()=="begueradj": 
      # Pop up the new interface if credentials are OK 
      self.item_insertion_window() 
     else: 
      # Loop over the login interface if not 
      self.initialize_user_interface() 

3.第二接口實現:

如果憑據是正確的,則顯示插入窗口到喜愛的明星加入到數據庫中。要彈出新窗口,您需要使用Tkinter.Toplevel()方法。

def item_insertion_window(self): 
     """ Display the stars to add to the database 
     Group the stars using radio buttons 
     """ 
     self.new_window=Tkinter.Toplevel(self) 
     self.new_window.wm_title("Add my favorite stars") 
     self.new_window.grid_rowconfigure(0, weight=1) 
     self.new_window.grid_columnconfigure(0, weight=1) 

     self.exitb=Tkinter.Button(self.new_window,text="Exit",command=self.new_window.quit) 
     self.submitb=Tkinter.Button(self.new_window,text="Submit",command=self.increment_db) 
     self.exitb.grid(row=8,column=1) 
     self.submitb.grid(row=8,column=0,sticky=Tkinter.W) 

     self.v=IntVar() 
     self.tvstars=[('YOWERI KAGUTA MUSEVENI', 1), ('KIIZA BESIGYE', 2), 
         ('AMAAMA JOHN MBABAZI ', 3), ('KARUNGI SHARON', 4), 
         ('BYAMUKAMA OSCAR', 5), ('MATILDA MOREEN', 6), 
         ('DUNCANS', 7)] 
     self.i=0 
     for self.txt, star in self.tvstars: 
      self.i=self.i+1 
      self.rb=Tkinter.Radiobutton(self.new_window,text=self.txt,variable=self.v,value=star) 
      self.rb.grid(row=self.i,column=0,sticky=Tkinter.W) 

4.如何獲得Tkinter的單選按鈕文本:

這是由函數item_insertion_window()做了什麼?

在官方文檔中,只有一種方法可以檢索所選擇的單選按鈕的值,但沒有辦法提到實際上對我們感興趣的文本(恆星名稱)。我沒有在StackOverflow上找到任何關於這個主題的帖子。我的黑客是編寫一本字典使用which_artist()功能的單選按鈕值對應的明星的名字映射:

def which_artist(self,radiob): 
     """Return star's name 
     """ 
     self.artists = { 
         1:"YOWERI KAGUTA MUSEVENI", 
         2:"KIIZA BESIGYE", 
         3:"AMAAMA JOHN MBABAZI", 
         4:"KARUNGI SHARON", 
         5:"BYAMUKAMA OSCAR", 
         6:"MATILDA MOREEN", 
         7:"DUNCANS", 
     } 
     return self.artists.get(radiob,"Unknown") 

,此功能將在接下來的步驟是有用的。

5.添加自己喜歡的明星到數據庫:

首先,你可能會節省你的MySQL服務器參數配置文件config.py,但由於我們的項目是小,顯然你不會把它擴大在未來的危機進一步,讓我們保存的功能本身這些憑據:

self.config = { 
        'user': 'begueradj', 
        'passwd': 'begueradj', 
        'host': '127.0.0.1', 
        'db': 'begueradj', 
     } 

這裏是實現插入功能:

def increment_db(self): 
    """ Insert the selected favorite star into the database. 
    """ 
    self.chosenartist=self.which_artist(self.v.get()) 
    print self.chosenartist 

    self.config = { 
       'user': 'begueradj', 
       'passwd': 'bregredj', 
       'host': '127.0.0.1', 
       'db': 'begueradj', 
    } 
    try: 
     self.connecttodb=MySQLdb.connect(**self.config) 
    except MySQLdb.Error: 
     print"Connexion error" 

    self.cursor=self.connecttodb.cursor() 

    self.cursor.execute("""INSERT INTO testtable(starname) VALUES(%s)""",self.chosenartist) 

    self.connecttodb.commit() 
    self.connecttodb.close() 

當然,您需要根據自己的設置更改配置字典self.config

此外,它更適合將self.connecttodb.close()綁定到退出按鈕self.exitb6.應用程序:

以下是完整的程序:

''' 
Created on Feb 29, 2016 

@author: begueradj 
''' 
import Tkinter 
import MySQLdb 
from Tkinter import IntVar 


class Begueradj(Tkinter.Frame): 
    ''' 
    classdocs 
    ''' 


    def __init__(self, parent): 
     ''' 
     Constructor 
     ''' 
     Tkinter.Frame.__init__(self, parent) 
     self.parent=parent 
     self.initialize_user_interface() 

    def initialize_user_interface(self): 
     """Draw a user interface allowing the user to type 
     MySQL server credentials 
     """ 
     self.parent.title("DB operations")  
     self.parent.grid_rowconfigure(0,weight=1) 
     self.parent.grid_columnconfigure(0,weight=1) 
     self.parent.config(background="lavender") 

     self.label_user=Tkinter.Label(self.parent,text="DB User: ",anchor=Tkinter.W,background="dark slate gray",foreground="white", font="Helvetica 8 bold") 
     self.label_password=Tkinter.Label(self.parent,text="DB Password:", anchor=Tkinter.W,background="dark slate gray",foreground="white", font="Helvetica 8 bold") 

     self.label_user.grid(row=0,column=0,sticky=Tkinter.E+Tkinter.W) 
     self.label_password.grid(row=1,column=0, sticky=Tkinter.E+Tkinter.W) 

     self.dbuser=Tkinter.Entry(self.parent) 
     self.dbpassword=Tkinter.Entry(self.parent,show="*") 

     self.dbuser.grid(row=0,column=1,sticky=Tkinter.E+Tkinter.W) 
     self.dbpassword.grid(row=1,column=1,sticky=Tkinter.E+Tkinter.W) 

     self.connectb=Tkinter.Button(self.parent,text="Log in",font="Helvetica 10 bold",command=self.dbconnexion) 
     self.cancelb=Tkinter.Button(self.parent,text="Cancel",command=self.parent.quit,font="Helvetica 10 bold") 

     self.connectb.grid(row=2,column=1,sticky=Tkinter.W) 
     self.cancelb.grid(row=2,column=2) 

    def item_insertion_window(self): 
     self.new_window=Tkinter.Toplevel(self) 
     self.new_window.wm_title("Add my favorite stars") 
     self.new_window.grid_rowconfigure(0, weight=1) 
     self.new_window.grid_columnconfigure(0, weight=1) 

     self.exitb=Tkinter.Button(self.new_window,text="Exit",command=self.new_window.quit) 
     self.submitb=Tkinter.Button(self.new_window,text="Submit",command=self.increment_db) 
     self.exitb.grid(row=8,column=1) 
     self.submitb.grid(row=8,column=0,sticky=Tkinter.W) 

     self.v=IntVar() 
     self.tvstars=[('YOWERI KAGUTA MUSEVENI', 1), ('KIIZA BESIGYE', 2), 
         ('AMAAMA JOHN MBABAZI ', 3), ('KARUNGI SHARON', 4), 
         ('BYAMUKAMA OSCAR', 5), ('MATILDA MOREEN', 6), 
         ('DUNCANS', 7)] 
     self.i=0 
     for self.txt, star in self.tvstars: 
      self.i=self.i+1 
      self.rb=Tkinter.Radiobutton(self.new_window,text=self.txt,variable=self.v,value=star) 
      self.rb.grid(row=self.i,column=0,sticky=Tkinter.W) 


    def which_artist(self,radiob): 
     self.artists = { 
         1:"YOWERI KAGUTA MUSEVENI", 
         2:"KIIZA BESIGYE", 
         3:"AMAAMA JOHN MBABAZI", 
         4:"KARUNGI SHARON", 
         5:"BYAMUKAMA OSCAR", 
         6:"MATILDA MOREEN", 
         7:"DUNCANS", 
     } 
     return self.artists.get(radiob,"Unknown") 

    def increment_db(self): 
     #print self.v.get() 
     self.chosenartist=self.which_artist(self.v.get()) 
     print self.chosenartist 

     self.config = { 
        'user': 'begueradj', 
        'passwd': 'begueradj', 
        'host': '127.0.0.1', 
        'db': 'begueradj', 
     } 
     try: 
      self.connecttodb=MySQLdb.connect(**self.config) 
     except MySQLdb.Error: 
      print"Connexion error" 

     self.cursor=self.connecttodb.cursor() 

     self.cursor.execute("""INSERT INTO mystars(starname) VALUES(%s)""",self.chosenartist) 

     self.connecttodb.commit() 
     self.connecttodb.close() 



    def dbconnexion(self):   
     if self.dbuser.get()=="begueradj" and self.dbpassword.get()=="begueradj": 
      self.item_insertion_window() 
     else: 
      self.initialize_user_interface() 



def main(): 
    root=Tkinter.Tk() 
    d=Begueradj(root) 
    root.mainloop() 

if __name__=="__main__": 
    main() 

7.演示

我插入穿過Tkinter的接口中的一個星。讓我們來檢查一下是否有效:

mysql> SELECT * FROM begueradj.mystars; 
+----+------------------------+ 
| id | starname    | 
+----+------------------------+ 
| 1 | YOWERI KAGUTA MUSEVENI | 
+----+------------------------+ 
1 row in set (0.00 sec) 

希望這會有所幫助。

UPDATE:

你問我有關如何更新,但是當涉及到理解你update語句的邏輯您的意見是,我不清楚。所以我只能根據你評論中顯示的一小段代碼回答。

您似乎想要檢查通過您的語句選擇哪個單選按鈕:self.var.get()並增加1(這就是爲什麼我不明白您的更新聲明:因此,無論按下哪個單選按鈕,您都會執行相同的操作;這意味着單選按鈕是沒有意義的)。

如果你想在你自己的一些神祕測試的角度來做到這一點,你需要使用variable選項,並將方法綁定到您創建的每個單選按鈕的command選項。

要使用variable選項,你將需要運行這個第一:

self.v = IntVar() 

然後,對於每個單選按鈕設置:variable=self.vcommand = self.get_radiobutton_id

有問題的方法必須返回的標識符選定的單選按鈕:

self defself.get_radiobutton_id(self): 
    return v.get() 
+1

非常感謝,它真的幫了我 –

+0

嗨賬單,我再次請求你的幫助,而不是插入聲明我想用單選按鈕的值更新表。我用「更新表名SET計數= 2其中ID =」self.v.get()「」,它有一個錯誤,self.v代表單選按鈕的值。 –

+0

我可以改變什麼,我將不勝感激 –