我将逐步指导您解决问题。我假设你已经在 Ubuntu 上安装了 MySQL 服务器。
无论您使用的是 Tkinter 还是其他一些 GUI 包,实现目标的方法都是一样的。
我需要使用哪些工具?
首先,您需要安装一个 Python 数据库接口,它允许您使用 Python 与 MySQL 服务器进行通信。这是详尽的list of Python MySQL databse interfaces。
哪一个更好安装?我更喜欢只谈论我自己使用过的两个:MySQLdb 和 MySQL connector。
MySQLdb 是一个 C 库,它比纯 Python 库的 MySQL 连接器更快。为了便携性,最好选择后者。为了速度,您需要选择第一个。请注意,Django 使用 MySQLdb。这也是我将在下文中使用的最喜欢的数据库界面。你可以在here这两个接口之间找到一个很好的比较。
如何在 Ubuntu 14.04.3 LTS 上安装 MySQLdb?
安装 MySQLdb 的常用方法是使用pip,如here 所述。但是对于 Ubuntu,根据我的个人经验,我更喜欢这样安装:
- 安装需要的依赖:
sudo apt-get install build-essential python-dev libmysqlclient-dev
- 自行安装 MySQL 数据库接口:
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()方法。
这是由函数item_insertion_window()完成的:
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 单选按钮文本?
在官方文档中,只有一种方法可以检索被选中的单选按钮的值,但没有提到获取我们真正感兴趣的文本(星星的名称)的方法。我也没有在 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)
希望这会有所帮助。
更新:
您问我如何更新,但在理解更新语句的逻辑时,我不清楚您的 cmets。所以我在这里只根据你评论显示的一小段代码来回答。
您似乎想通过您的声明检查选择了哪个单选按钮: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()