1

I am learning Tkinter and have made a program (just for practice) which takes user input in Entry field and save what the user has entered in a MySQL database by clicking submit button.

Code:

from tkinter import *
import tkinter
import mysql.connector
from tkinter import *
import mysql.connector
import random

DB = mysql.connector.connect(
    host = "localhost",
    user = "Lincoln",
    password = "lincoln110904@",
    database = "test"
)
cursor = DB.cursor()

gui2 = Tk()
gui2.title("Airline Ticket Booking System")
gui2.iconbitmap("C:/Users/keepa/OneDrive/Desktop/icon.ico")
gui2.maxsize(width=1000, height=70)
gui2.minsize(width=1000, height=700)



data = Entry(gui2,  text = 'food name', textvariable="data_var")
data.pack()
data_var = tkinter.StringVar(data).get()

user_id = random.randint(1128, 9721)

def submit_it():
    sql = "INSERT INTO user_time(user_id, time) VALUES(%s, %s)"
    values = (user_id, str(data_var))
    cursor.execute(sql,values)
    DB.commit()

submit = Button(gui2, text = 'submit', command=submit_it)
submit.pack() 

gui2.mainloop()

Output in MySQL database: OUTPUT

Anyone, please help why the data in the time row is empty/blank?

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
  • 1
    There are two issues: 1) used string "data_var" for `textvariable` option; 2) get the value just after the `StringVar` is created which will get empty string. – acw1668 Jan 13 '22 at 04:27

1 Answers1

1

You need to:

  • use reference of a StringVar instead of string for the textvariable option
  • get the input content when it is needed instead of getting it just after the entry is created:
...
data_var = tkinter.StringVar()
data = tkinter.Entry(gui2, text='food name', textvariable=data_var)
...
def submit_it():
    sql = "INSERT INTO user_time (user_id, time) VALUES (%s, %s)"
    # get the input data from the Entry here
    values = (user_id, data_var.get())
    cursor.execute(sql, values)
    DB.commit()

Also note that wildcard import is not recommended.

acw1668
  • 40,144
  • 5
  • 22
  • 34