0

how do i solve the following problem i am unable to get text from QTextEdit and insert it into Database...

Code:

import sys
import MySQLdb
#from PyQt4.QtCore import *
from PyQt4.QtGui import *

e1=None
e2=None

def window():
    app=QApplication(sys.argv)
    win=QWidget()
    win.setWindowTitle("Sample")
    vbox=QVBoxLayout()
    e1 = QTextEdit()
    e2 = QTextEdit()
    vbox.addWidget(e1)
    vbox.addWidget(e2)
    vbox.addStretch()
    b1=QPushButton("Tap it!")
    vbox.addWidget(b1)
    b1.clicked.connect(b1_action)
    win.setGeometry(100,100,200,50)
    win.setLayout(vbox)
    win.show()
    sys.exit(app.exec_())

def b1_action():
    print "Button Clicked"
    db = MySQLdb.connect('localhost', 'root', 'mysql', 'Tecoc354')
    cursor=db.cursor()
    x1=e1.toPlainText()
    x2=e2.toPlainText()
    print x1," ",x2," "
    #sql="create table Sample(addr varchar(10),name varchar(10))"
   # cursor.execute(sql)
    sql2="insert into Tecoc354.sample values(%s,%s)"%(x1,x2)
    cursor.execute(sql2)
    db.commit()
    db.close()

window()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

0

The problem here is, that in b1_action() the variables e1 and e2 are not recognized as QTextEdit(). Just for educational purpose add the line print e1 to both functions. You'll get:

<PyQt4.QtGui.QTextEdit object at 0x01DA7490>
none

printed from Window() and b1_action(). So you see, in b1_action() e1 is not a QTextEdit. e1 / e2 in Window() are not the same variables as e1 / e2 in b1_action()

The shortest way to solve that is to make e1 and e2 global variables. So first delete the lines

e1=None
e2=None

and then define both variables as global inside of Window:

from PyQt4.QtGui import *

def window():
    global e1
    global e2
    app=QApplication(sys.argv)
    win=QWidget()
    win.setWindowTitle("Sample")
    vbox=QVBoxLayout()
    e1 = QTextEdit()
    e2 = QTextEdit()

You can find some useful information in this question and answers about global variables

Generally I would not recommend to build a GUI based on functions and global variables. Find a tutorial and learn how to use classes. For example this one

jps
  • 20,041
  • 15
  • 75
  • 79