python - How to get input from QTextEdit in PyQt4 -
how solve following problem unable text qtextedit , insert database...
code:
import sys import mysqldb #from pyqt4.qtcore import * 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 tecoc354.sample values(%s,%s)"%(x1,x2) cursor.execute(sql2) db.commit() db.close() window()
the problem here is, in b1_action() variables e1 , e2 not recognized qtextedit(). educational purpose add line print e1 both functions. you'll get:
<pyqt4.qtgui.qtextedit object @ 0x01da7490> none printed window() , b1_action(). see, in b1_action() e1 not qtextedit. e1 / e2 in window() not same variables e1 / e2 in b1_action()
the shortest way solve make e1 , e2 global variables. first delete lines
e1=none e2=none and define both variables 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 useful information in question , answers global variables
generally not recommend build gui based on functions , global variables. find tutorial , learn how use classes. example this one
Comments
Post a Comment