我将逐步指导您解决您的问题。我假设你已经在Ubuntu上安装了MySQL服务器。
无论您是使用Tkinter还是其他一些GUI软件包,实现目标的方法都是一样的。
我需要使用哪些工具?
首先,您将需要安装一个Python数据库接口,该接口将允许您使用Python与MySQL服务器进行通信。这里是详尽的list of Python MySQL databse interfaces。
哪一个更好安装?我更愿意谈谈我自己使用的其中的两种:MySQLdb和MySQL 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服务器:
如果证书不正确,窗口仍会在那里提示自己,除非用户存在该应用程序。
如果凭据是正确的,然后用户可以保存/他最喜欢的开始,通过类似于你设计了一个新的窗口添加到数据库:
实现应用程序:
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.exitb
。 6.应用程序:
以下是完整的程序:
'''
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.v
和command = self.get_radiobutton_id
有问题的方法必须返回的标识符选定的单选按钮:
self defself.get_radiobutton_id(self):
return v.get()
这些按钮项与您的数据库之间的关系是什么?您是否尝试执行插入,删除,显示或...? –
只要选择了raibutton并按下提交按钮,就更新表格。更新按1递增。 –