我想用数据库查询的结果填充 ttk.combobox [英] I want to populate a ttk.combobox with results from database query

查看:41
本文介绍了我想用数据库查询的结果填充 ttk.combobox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题需要帮助.这与 python ttk.combobox 小部件有关我是 python 的新手,一周前才开始编码.我有一个由用户输入填充的数据库.该数据库用于存储用户的库存输入(例如项目、成本、供应商等).这部分我已经能够做到.

i am having a little problem i would need help with.This concerns python ttk.combobox widget I am new to python just started coding a week ago. I have a database which is populated by user input.This database is to store a user's stock input(e.g. items, cost, supplier ,etc).This part i have been able to do.

从数据库中,我使用for"循环将我的数据库查询中的每个单独项目放入 ttk.combobox,以便用户可以进行选择.但是我的问题是,我每次都会出错.我希望组合框从我的数据库查询中显示我的项目列中的所有项目.

From the database, am using a 'for' loop to get each seperate item from my database query into a ttk.combobox so a user can make selections. However my problem is,i get an error everytime. I want the combobox to show all items within my item column from my database query.

从在线资源中,我找到了 ttk.combobox 的示例:

From online sources ,i found out an example for ttk.combobox:

    list = ['shoe', 'toy', 'bag']
    combobox = ttk.Combobox(root)
    combobox['values'] = list

这很好用,如果我要使用自制列表但是,我找不到在 python 中使用 sqlite3 查询的 ttk.combobox 示例

This works fine,if i am to use a self-made list However , i can't find an example for a ttk.combobox using query from sqlite3 in python

提前感谢您帮助我解决这个问题.如何做到这一点的一个例子以及我做错了什么的解释会对我有很大帮助.请原谅我组织得不好的编码风格,我希望随着时间的推移变得更好.

Thank you in advance for helping me out with this problem. An example of how to do it and an explanation of what i did wrong will help me alot. Forgive me for my poorly organised coding style,i hope to get better at it as time goes on.

from tkinter import *
from tkinter import ttk
import sqlite3

class Example:
    def __init__(self,master):
     self.master = master
     self.win_label = Label(master, text="New Stock Entry")
     self.win_label.grid(row=0, columnspan=2,)
     self.item_label = Label(master, text="Item Name", fg='black')
     self.item_label.grid(row=1, column=0, sticky=W, padx=5, pady=5)
     self.unitprice_lab = Label(master, text="Unit Price", fg='black')
     self.unitprice_lab.grid(row=2, column=0, sticky=W, padx=5, pady=5)
     self.total_price = Label(master, text="Total Price", fg='black')
     self.total_price.grid(row=3, column=0, sticky=W, padx=5, pady=5)
     self.quantity_lab = Label(master, text="Quantity", fg='black')
     self.quantity_lab.grid(row=4, column=0, sticky=W, padx=5, pady=5)
     self.manufacturer_lab = Label(master,text="Manufacturer", fg='black')
     self.manufacturer_lab.grid(row=5, column=0, sticky=W, padx=5, pady=5)

      ############### Variables to store input ################
     self.item = StringVar()
     self.unitp = IntVar()
     self.unitn = IntVar()
     self.quantity = IntVar()
     self.man = StringVar()

     ############ Widgets############
     self.item_entry = Entry(master, width=25,textvariable=self.item)
     self.item_entry.grid(row=1, column=1, padx=5, pady=5)
     self.unitprice_entry = Entry(master, width=25,textvariable=self.unitp)
     self.unitprice_entry.grid(row=2, column=1, sticky=W, padx=5, pady=5)
     self.total_price_entry = Entry(master,width=25,textvariable=self.unitn)
     self.total_price_entry.grid(row=3, column=1, sticky=W, padx=5, pady=5)
     self.quantity_entry = Entry(master,width=25,textvariable=self.quantity)
     self.quantity_entry.grid(row=4, column=1, sticky=W, padx=5, pady=5)
     self.manufacturer_entry = Entry(master, width=25,textvariable=self.man)
     self.manufacturer_entry.grid(row=5, column=1, sticky=W, padx=5, pady=5)
     # button for save
     self.button_save = Button(master,text="Save",command= self.insert_Dbs)
     self.button_save.grid(row=6, column=1, pady=15, padx=10, sticky=W)

  def second_window(self):  # Second Window to allow user selection
    t = Toplevel()
    t.geometry('350x290')
    t.title('Student Input')

    ############# widgets ###############
    self.label1 = ttk.Label(t, text = 'Student Name')
    self.label1.grid(row =0 , column =0)
    self.label2 = ttk.Label(t, text='Item Collected')
    self.label2.grid(row=0, column=1)
    self.label3 = ttk.Label(t, text='Quantity')
    self.label3.grid(row=0, column=2)
    self.entry1 =ttk.Entry(t, width = 20)
    self.entry1.grid(row =1 , column =0)
    self.entry2 = ttk.Entry(t, width=20)
    self.entry2.grid(row=1, column=2)
    self.comb = ttk.Combobox(t,width = 15).grid(row =1 , column =1)
    self.comb['value'] = self.combo_input


  def insert_Dbs(self): # Function to insert input into database

    self.a1 = self.item.get()
    self.a2 = self.unitp.get()
    self.a3 = self.unitn.get()
    self.a4 = self.quantity.get()
    self.a5 = self.man.get()

    #db = sqlite3.connect('stockdbExample.db')
    '''db.execute('create table stocks (item text '
               ', item_uprice integer,'
               '  item_nprice integer,'
               ' quantity integer,'
               ' manufacturer text )')'''
    db = sqlite3.connect('stockdbExample.db')
    db.execute('insert into stocks (item,'
               ' item_uprice,'
               ' item_nprice,'
               ' quantity,'
               ' manufacturer) values (?, ?, ?, ?,?)',
               (self.a1, self.a2, self.a3, self.a4, self.a5))
    db.commit()
    self.combo_input()
    self.second_window()

  def combo_input(self):
    db = sqlite3.connect('stockdbExample.db')
    cursor = db.execute('select item from stocks')
    for row in cursor.fetchall():
        return row

root = Tk()
c = Example(root)
root.mainloop()

推荐答案

第一:你忘记了()执行函数

First: you forgot () to execute function

self.comb['value'] = self.combo_input()

第二:在 combo_input 里面你使用 return row 所以你只返回第一行,仅此而已.

Second: inside combo_input you use return row so you return only first row, nothing more.

您必须创建包含所有值的 Python 列表,然后返回它.
它可以是这样的:

You have to create Python list with all values and then return it.
It can be something like this:

def combo_input(self):
    db = sqlite3.connect('stockdbExample.db')
    cursor = db.execute('select item from stocks')

    result = []

    for row in cursor.fetchall():
        result.append(row[0])

    return result

<小时>

完整的工作示例:

import tkinter as tk
import tkinter.ttk as ttk
import sqlite3

class Example:

  def __init__(self,master):
     self.master = master

     self.db = sqlite3.connect('stockdbExample.db')

     # use only once
     self.create_db()   

     self.cb = ttk.Combobox(master)
     self.cb.pack()
     self.cb['values'] = self.combo_input()

  def combo_input(self):
    cursor = self.db.cursor()

    cursor.execute('SELECT item FROM stocks')

    data = []

    for row in cursor.fetchall():
        data.append(row[0])

    return data

  def create_db(self):

    cursor = self.db.cursor()
    cursor.execute('CREATE TABLE stocks (item text)')
    cursor.execute('INSERT INTO stocks (item) VALUES("Hello")')
    cursor.execute('INSERT INTO stocks (item) VALUES("World")')
    cursor.execute('INSERT INTO stocks (item) VALUES("Tkinter")')
    cursor.close()

    self.db.commit()

root = tk.Tk()
Example(root)
root.mainloop()

这篇关于我想用数据库查询的结果填充 ttk.combobox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆