In this lesson we are going to talk about TKinter MySQL Database, we want to learn how you can connect your tkinter application with mysql database.
First of all you need to download Wamp Server, because we are going to create our database in wamp server, after that create a database in the wamp server, you can give any name for your database, i have give tkdb.
Also you need to install MySQLdb, MySQLdb is an interface to the popular MySQL database server that provides the Python database API. originally MySQLdb was for Python 2.7, but there another version of MySQLdb that is called MysqlClient, and it supports Python 3.0, at the writing of this article MysqlClient supports Python 3.0 up to 3.8, you can check their Documentation for more updates.
1 |
pip install mysqlclient |
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import tkinter as tk from tkinter import ttk import MySQLdb as mdb class Window(tk.Tk): def __init__(self): super(Window, self).__init__() self.title("TKinter DB Connection") self.minsize(300,250) self.wm_iconbitmap("myicon.ico") self.label_frame = ttk.LabelFrame(self, text = "Database Connection") self.label_frame.grid(column = 0, row =0, padx = 20, pady = 20) self.create_widgets() def create_widgets(self): button = ttk.Button(self.label_frame, text = "Connection Status", command = self.db_connect) button.grid(column = 0, row = 0) self.label = ttk.Label(self.label_frame, text = "") self.label.grid(column = 0, row = 1) def db_connect(self): try: db = mdb.connect('localhost', 'root', '', 'tkdb') self.label.configure(text = "Connected Successfully") except mdb.Error as e: self.label.configure(text = "Not Successfully Connected") window = Window() window.mainloop() |
We have created a button with a label, because we want to check mysql database connectivity.
1 2 3 4 5 6 |
button = ttk.Button(self.label_frame, text = "Connection Status", command = self.db_connect) button.grid(column = 0, row = 0) self.label = ttk.Label(self.label_frame, text = "") self.label.grid(column = 0, row = 1) |
Using this code we can connect our tkinter application to mysql database, you need to give host, username, password and database name in the parameters.
1 |
mdb.connect('localhost', 'root', '', 'tkdb') |
Run the complete code and click on the button this will be the result.