Link to home
Start Free TrialLog in
Avatar of Ahmad Sarairah
Ahmad Sarairah

asked on

problem with result of code

i have run this code but when i click on submit button the table stored with (self.firstName,self.lastName) not with the entered names by entry text box
code.png
code1.png
Avatar of mohan singh
mohan singh
Flag of India image

Hi Ahmad Sarairah
 
Can you Show your code for batter help

Thank You
Mohan Singh
Avatar of Ahmad Sarairah
Ahmad Sarairah

ASKER

yes you can see my code in this attached file
Still no file attached!
There is no attached file to view the code in. Screenshots would also be helpful.

User generated image
When Submit Button is clicked TextBox3.Text = Textbox1.Text + "." + Textbox2.Text
VB
 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TextBox3.Text = TextBox1.Text + "." + TextBox2.Text
    End Sub

Open in new window

It is unclear in your question whether you have TextBox3.Text and on Submit Button you want TextBox1.Text and TextBox2.text?
@David - this is a PHP Question ;)
i have edited my question with screenshot of running code

please help me
You still need to post the actual php code at text for us to look at
i have run this code but when i click on submit button the table stored with (self.firstName,self.lastName) not with the entered names by entry text box

this is the code :
#!c:\python27\python
from MySQLdb import *
from Tkinter import *
import sqlite3
import sys, random, math


class student:
    def __init__(self):

       
      self.root = Tk()
      self.root.title("Student Form")
      self.root.geometry('500x500')

      self.fName = StringVar()
      self.lName = StringVar()
     
    
# Code to add widgets will go here...
      self.connection = connect("localhost","testuser","test123","TESTDB")
      self.setupGUI()
      self.root.mainloop()
      

    def setupGUI(self):
        
      fName = Label(self.root, text="First Name",width=20)
      fName.place(x=80,y=130)
      E1 = Entry(self.root,textvariable=self.fName)
      E1.place(x=240,y=130)

      lName = Label(self.root, text="Last Name",width=20)
      lName.place(x=78,y=180)
      E2= Entry(self.root,textvariable=self.lName)
      E2.place(x=240,y=180)

      

      Button(self.root,text="Submit",padx=5,bg="red",fg="white",command=self.verify).place(x=270,y=340)

     
      

    def verify(self):
        
      self.firstName = self.fName.get()
      self.lastName = self.lName.get()
    

      if (self.firstName != "" and self.lastName != ""):
                print("All there!")
                self.datastore()

      else:
            print("Information is Missing,Please Check Your Inputs.")
    def datastore(self):

           print(self.firstName)
           print(self.lastName)
          
           if self.connection:
            print("DB Connection was a great success...")
            print("Now entering data...")
            self.connection.query("""INSERT INTO student (FIRST_NAME,LAST_NAME)
               VALUES ('self.firstName','self.lastName')""")
            self.connection.commit()
            self.connection.close()
           else:
            print("Failed To Connect to DataBase :c ")

if __name__ == "__main__":

 student()

Open in new window


and this screenshots with results :
code.png
and this this another screenshots of table
code1.png
The reason is probably hidden here:
"""INSERT INTO student (FIRST_NAME,LAST_NAME)
               VALUES ('self.firstName','self.lastName')"""

Open in new window


This is one big string, and the self.firstName and the self.lastName are just characters in the string. You need to put or textually the values there (simpler), or to use the command object and set the parameters (more work, and you have to add placeholders). The simpler would be like:
            self.connection.query("""INSERT INTO student (FIRST_NAME,LAST_NAME)
               VALUES ('{0}', '{1}')""".format(self.firstName, self.lastName))

Open in new window


Or even more understandable for beginners (without using .format:
            self.connection.query("INSERT INTO student (FIRST_NAME,LAST_NAME)  VALUES ('" + self.firstName + "', '" + self.lastName + "')")

Open in new window

(But be carefull with where the apostrophe is and wher the double quotes -- the single ones are inside the double quotes here.)

From Python 3.6, the formatted string literal is handy in such cases (https://docs.python.org/3/reference/lexical_analysis.html#f-strings):
            self.connection.query(f"INSERT INTO student (FIRST_NAME,LAST_NAME)  VALUES ('{self.firstName}', '{self.lastName}')")

Open in new window

Notice the f"..." at the beginning of the string literals.
thanks for all i have successfully run my code after using " .format"
hi all

how to insert birth of date in insert query  in above code with 'YYYY/DD/MM' with out any error

the error was as the screenshot

please help me
code3.png
student_form.py
The SQL engine expects dashes instead of slashes. Anyway, you can make your program to accept both. If slashes are used, then you can replace them in the string before using the string for the INSERT command, like this:
self.DOBirth = self.DOBirth.replace('/', '-')

Open in new window

thank you dear pepr
Hi all

how to add clear button function in this form
student_form.py
Hi all

how to make query button to show stored data in table

please help me
student_form.py
You are creating the entries E1 and E2 in the setupGUI method. Now, you will want to erase them. It means you need to access them later. Because of that, the first change is to add self. to get self.E1 and self.E2.

Then you add another button. The button must also be told, what method must be called when clicked. This is done via the command=self.clear argument.

The self.clear is nothing special. It is your own method that you need to add. (You can name it differently, but if named differently, you have to tell the button the other name.) Inside the self.clear, you access both entries, and you delete the text in the entries. This is done by calling the .delete(0, END) -- see the Tkinter tutorial.

    def setupGUI(self):
        fName = Label(self.root, text="First Name",width=20)
        fName.place(x=80,y=130)
        self.E1 = Entry(self.root,textvariable=self.fName)
        self.E1.place(x=240,y=130)

        lName = Label(self.root, text="Last Name",width=20)
        lName.place(x=78,y=180)
        self.E2= Entry(self.root,textvariable=self.lName)
        self.E2.place(x=240,y=180)

        Button(self.root,text="Submit",padx=5,bg="red",fg="white",command=self.verify).place(x=270,y=340)
        Button(self.root,text="Clear",command=self.clear).place(x=270, y=390)


    def clear(self):
        self.E1.delete(0, END)
        self.E2.delete(0, END)

Open in new window

thank s pepr

also i have created a query button to print  data from table but i have an error in this code .

this error showed in screenshot  when i clicked on query button :
student_form.py
code4.png
It says that the self.firstName was not created, yet. You call the code before the self.firstName was assigned any value.

Some more comments to the last part of the script...

You have to be carefull with indentation. The print should probably nested in the loop:
        for row in self.data:
            first_name = row[0]
            last_name = row[0]
        print "first_name,   last_name" \
              (self.firstName,self.lastName)

Open in new window

Then the last_name should probably be row[1] (I did not check carefully.

You should not mix the print and print() in Python 2. The reason is that you may get unexpected in the case when there is more than one argument. If you are forced to use Python 2 (say in school), you can use tell even Python 2 to use the future version of print like this:
from __future__ import print_function

Open in new window


Then you can you must use the print with parentheses.

When printing, you can pass the print a string or other values that are automatically converted to strings. You probably wanted to use a .format() that takes the template string (the one before the dot) and puts the arguments to the placeholders. You are missing both placeholders and the .format()

When not sure with printing, use the simplest form. Try to replace the above code by:
        for row in self.data:
            first_name = row[0]
            last_name = row[1]
            print(first_name, last_name)

Open in new window

or even
        for row in self.data:
            print(row[0], row[1])    # first name, last name

Open in new window

thank you pepr

the above code successfully done
Hi all

how to show query results in another window

pleas help me
student_form.py
Instead of using print, you have to build a string. Then you need to create a window. Inside the window, you probably want to create Label that will display the text. In your case, the simplest way may be to put everything to the query_table method like this
    def query_table(self):
        self.window = Toplevel(self.root)
        self.window.title('List of names')
        self.window.geometry('800x600')     
        
        self.db  = connect("localhost","testuser","test123","TESTDB")
        self.cursor = self.db.cursor()
        self.cursor.execute("SELECT * FROM STUDENT")
        self.db.commit()
        self.data = self.cursor.fetchall()
        lst = []
        for row in self.data:
            first_name = row[0]
            last_name = row[1]
            email = row[2]
            date_of_birth = row[3]
            gender = row[4]
            lst.append(first_name + "   " + last_name + "   " + email + "   " + date_of_birth + "   " + gender)

        w = Label(self.window, text='\n'.join(lst))
        w.pack()

Open in new window

Notice the window creation at the beginning, the lst used to collect string lines, the Label at the end, where '\n'.join(lst) joins the collected lines into one multiline string.
thanks pepr

also i want to show results of query in another window but as table like excel sheet or as tree in screenshot below
tree.png
I do not have any experience with grid view or tabular view in Tkinter. I do not know whether there is any control like that, in Tkinter.
thank you pepr

i would like to help me to make search button in this code to filter data by first_name or last_name or birth of date or any thing  .

please help me .
i would like to help me to make search button in this code to filter data by first_name or last_name or birth of date or any thing  .
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.