gpt4 book ai didi

python - 如何读取QComboBox数据并将其存入mysql数据库

转载 作者:行者123 更新时间:2023-11-30 21:53:00 25 4
gpt4 key购买 nike

如何从 QComboBox 中获取选定的项目,以及当单击按钮时将组合框的选定项目存储到数据库中...

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

def win():

db=MySQLdb.connect('localhost','root','Suhel786','radio')
cursor=db.cursor()

app=QApplication(sys.argv)

w=QWidget()
co=QComboBox()
co.addItem("A+")
co.addItem("A-")
b1 = QPushButton("Tap it!")
w.setWindowTitle("Combo")
hbox=QHBoxLayout()
hbox.addWidget(co)
hbox.addWidget(b1)

b1.clicked.connect(b1_action)

w.setLayout(hbox)

w.show()

db.commit()
db.close()

sys.exit(app.exec_())

def b1_action():
print "data is inserted"

win()

最佳答案

您必须将按钮的 clicked 信号连接到某个插槽,在这种情况下,插槽将是保存方法,在此函数中我们将通过 currentText( )QComboBox的方法,并将其插入到数据库中,如下所示:

class Win(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.db = MySQLdb.connect('localhost','root','Suhel786','radio')
self.cursor = self.db.cursor()

self.db.commit()
self.setLayout(QHBoxLayout())
self.btn = QPushButton("Save", self)
self.combo = QComboBox(self)
self.combo.addItems(["A+", "A-", "AB-"])
self.layout().addWidget(self.btn)
self.layout().addWidget(self.combo)
self.btn.clicked.connect(self.save)

def save(self):
text = self.combo.currentText()
self.cursor.execute("INSERT INTO test (Blood) values('{}')".format(text))
self.db.commit()


if __name__ == '__main__':
app = QApplication(sys.argv)
w = Win()
w.show()
sys.exit(app.exec_())

关于python - 如何读取QComboBox数据并将其存入mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46398817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com