如何从mysql db中获取数据并将其插入到Python中的mysqldb的wx.ComboBox中

时间:2012-02-06 22:03:44

标签: python wxpython mysql-python

我在wxpython中创建了一个面板,加上我有一个数据库(MySQLdb),然后我从我的数据库中选择一些数据,我想将它们插入到wx.Combobox(下拉列表)中,之后如果选择是A选择或B选择我想从列表框中的数据库中插入一些其他数据。代码如下:

import MySQLdb
import sys
import wx

APP_SIZE_X = 661
APP_SIZE_Y = 319

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, 
        size=(APP_SIZE_X, APP_SIZE_Y))

        panel = wx.Panel(self, -1,style=wx.SUNKEN_BORDER)

        sel="Make your choice"
        wx.StaticText(panel, -1,sel,(15,10))

            db=MySQLdb.connect(host="localhost",use_unicode="True",
                    charset="utf-8",
        user="youruser",passwd="somepwd",db="choicedb")

        cursor=db.cursor()
        sql="""SELECT name from choicetb"""

        cursor.execute(sql)

        rows = cursor.fetchall()

        for row in rows:

                  print row[1]



            sampleList = ["A choice", "B choice", "C choice"]#The data from db
            wx.ComboBox(panel, -1, "A choice", (15, 30), 
            wx.DefaultSize,sampleList, wx.CB_DROPDOWN)

        math="Selected items"
        wx.StaticText(panel, -1,math,(10,100))

        listBox = wx.ListBox(panel, -1, (10, 130), (230, 120),
        ' ', wx.LB_SINGLE)


        exitbutton =wx.Button(panel,-1, label="Quit", pos=(300, 230))
        exitbutton.Bind(wx.EVT_BUTTON, self.OnQuit)
        self.Centre()

    def OnQuit(self, e):

        self.Close()

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'form1.py')
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

app = MyApp(0)
app.MainLoop()

我如何插入我在组合框中选择的选项,我尝试了一些但是它给了我最后的选择。我知道内部循环但是什么?感谢您的回答和您的帮助。

1 个答案:

答案 0 :(得分:1)

将新数据放入Python列表,然后使用ListBox的/ ComboBox的AppendItems(your_list)方法。这可能是最简单的方法。如果你已经有了组合框的列表,你可以这样做:

self.myComboList = ["some", "list"]
for row in rows:
   self.myComboList.Append(row[1])
self.ComboList.sort()
self.myComboBoxWidget.AppendItems(self.ComboList)

这样的事情应该有用。