Inserting data from TKinter GUI to web page using request
We are submitting user inputs from Tkinter window to a webpage by using request. We will submit data using a post method. Here is a sample data submission and getting message from website.
If you want to use the same target URL as shown above, on success you will get return message with the input name and one fixed id. Say if your name input is Alex then you will get return text as this.
Alex id=55
Here is the sample PHP script which receives the POST data and insert the same into student table.
<?Php
$host_name = "localhost";
$database = "database_name"; // Change your database name
$username = "root"; // Your database user id
$password = "password"; // Your password
try {
$dbo = new PDO('mysql:host='.$host_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . " ";
die();
}
// database connection is over ///
$name=$_POST['name']; // Collect name
$class=$_POST['class'];
$mark=$_POST['mark'];
$gender=$_POST['gender'];
$status='T';// fixing status vlaue for validation
$query="insert into student(name,class,mark,gender)
values(:name,:class,:mark,:gender)";
$step=$dbo->prepare($query);
$step->bindParam(':name',$name,PDO::PARAM_STR, 15);
$step->bindParam(':class',$class,PDO::PARAM_STR, 15);
$step->bindParam(':mark',$mark,PDO::PARAM_INT,3);
$step->bindParam(':gender',$gender,PDO::PARAM_STR,10);
if($step->execute()){
$mem_id=$dbo->lastInsertId();
echo " $name id = $mem_id ";
}
else{
echo " Not able to add data please contact Admin ";
}
?>
User will enter four input data using our Tkinter window. Main components are here
Name : String of name through a text box t1 Class : Select one option from the dropdown OptionMenu Mark : Integer value ( number ) through text box t3 gender : Selection through a pair of radio buttons ( Male , Female or other ) Submit : Button to trigger a click event to handle all the inputs.
Using Request
import requests
Layout and adding Widgets
There are Labels to show message about the input data ( l1,l2,l3 ) and one final Label ( l5 ) to display the output or return id of the record after inserting the data in table. One OptionMenu ( opt1) is used for selection of class.
Inside the function add_data() we have two sections. In first section we will check each input data. It is expected that no input is left blank by user. Without filling the details if user has clicked the button ( b1 ) then we will display a message through our Label ( l5 ) asking to check the inputs ( Read the else part of the if-else).
def add_data():
flag_validation=True # set the flag
my_name=t1.get("1.0",END) # read name
my_class=options.get() # read class
my_mark=t3.get("1.0",END) # read mark
my_gender=radio_v.get() # read gender
# length of my_name , my_class and my_gender more than 2
if(len(my_name) < 2 or len(my_class)<2 or len(my_gender) < 2 ):
flag_validation=False
try:
val = int(my_mark) # checking mark as integer
except:
flag_validation=False
if(flag_validation):
# Part 3 Send the request with data to target URL
else:
l5.config(fg='red') # foreground color
l5.config(bg='yellow') # background color
my_str.set("check inputs.")
In this code we first set one flag validation ( flag_validation ) to True, if any where the validation of the inputs fails then we will change this status of validation to False. ( this is part of the above code )
if(len(my_name) < 2 or len(my_class)<2 or len(my_gender) < 2 ):
flag_validation=False
try:
val = int(my_mark) # checking mark as integer
except:
flag_validation=False
After all the checks ( validation of inputs ) if the flag ( flag_validation ) is True , then we can insert data to Excel file and save the file.
if flag_validation:
# url = "https://www.plus2net.com/python/tkinter-post-return.php"
url = "http://localhost/plus2net/python/tkinter-post-return.php"
data = {
"name": my_name,
"class": my_class,
"mark": my_mark,
"gender": my_gender,
}
my_return = requests.post(url, data=data)
print(my_return.text)
t1.delete("1.0", END) # reset the text entry box
t3.delete("1.0", END) # reset the text entry box
l5.config(fg="green")
l5.config(bg="white")
my_str.set(my_return.text)
l5.after(2000, lambda: my_str.set(""))
Adding a time delay
We want to show the ID ( after adding the record ) or the error message for some time ( say 3 seconds ) and it should vanish after the time delay.