How to Connect Python TKinter with MySQL

In this Python TKinter article we want to learn How to Connect Python TKinter with MySQL,

you will learn that how you can use MySQLdb or MysqlClient, a third party library for

database programming in Python.

 

 

What is 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.

 

 

 

 

Installation 

You can simply use pip for the installation.

 

 

 

Also you need to install Wamp Server, after installation of the Wamp Server, you need to

open Wamp Server and create a database, iam going to call tkdb.

TKinter Database Creation
TKinter Database Creation

 

 

 

OK now this is the complete code for How to Connect Python TKinter with MySQL.

 

 

At the top we have create our main class that extends from tkinter.Tk, and if you want to

add title than you can use this code.

 

 

This is used for setting the min size of the window.

 

 

In here we want to add icon for our window. make sure that you have already

added an icon in your working directory.

 

 

This is our LabelFrame, so a labelframe is a simple container widget. Its primary purpose

is to act as a spacer or container for complex window layouts.

 

 

 

OK in here we have created a button, and you can see that we have connected the command

button with db_connect() method, so this is the method that we want to our Mysql Connection

with TKinter.

 

 

You can use MySQLdb.connect() for connection to mysql database, you need to pass

the hostname,username,password and database name. in our case for the hostname we

use localhost, for username we use root, for password we leave it blank because we don’t

have any password and for database name we can give our db name.

 

 

 

Run the complete code and this is the result.

How to Connect Python TKinter with MySQL
How to Connect Python TKinter with MySQL

 

 

Thank you for visiting my website! If you enjoyed the free courses, please consider supporting my works on Patreon.

Leave a Comment