How to extract a particular row value on inputting value of a particular row

允我心安 提交于 2019-12-11 23:13:57

问题


I want to make a GUI program that inputs the value of a column the program must go to the row where the inputted value is equal to the row value and display the particular row value in a text box but I am clueless on how to do this.

I tried using while loop to do it so it will search the whole excel file to check whether value of inputted data is equal to the data in the textbox but it did not go properly.

I am using python 3.7.0 using anaconda.

from tkinter import *
import openpyxl

a = Tk()
a.title('Return Book')
a.geometry('500x200')
heading = Label(a,text = 'Return Book')
heading.grid(row = 0,column = 1)
lab1 = Label(a,text = 'Enter Invoice Number:')
lab1.grid(row = 1, column = 0)
inv_field = Entry(a)
inv_field.grid(row = 1, column = 1)
inv_field.get()
find = Button(a,text = 'Find',width = 4,command =a.destroy)
find.grid(row = 2, column = 1)


def find():
    ##extradiction
    ##location of excel file
    path = "E:\Library Management\issue.xlsx"
    # workbook object is created 
    wb = openpyxl.load_workbook(path)   
    sheet = wb.active 
    max_col = sheet.max_column 

    # Will print a particular row value 
    for i in range(1, max_col + 1): 
    cell_obj = sheet.cell(row = 2, column = i) 
    print(cell_obj.value, end = " ")



a.mainloop()

I expect the program to input the value of the invoice number and search the whole database for the number and print the row in the textbox.


回答1:


First you did not define the textbox in your code to show the search result. Second you use a.destroy in command option of find button, it should be set to find function. Also you use same name find for find button and find function.

Suggest to add a Text widget:

book_info = Text(a, width=40, height=5)
book_info.grid(...)

Then rename find() function to find_book() and add a new update_text() to show the search result as below:

def update_text(info):
    book_info.delete(1.0, 'end')
    book_info.insert('end', info)

def find_book():
    inv_no = inv_field.get()
    if inv_no:
        wb = openpyxl.load_workbook('E:\Library Management\issues.xlsx')
        sheet = wb.active
        for row in sheet.rows:
            # assume invoice no is in column 1
            if row[0].value == inv_no:
                update_text('\n'.join(str(cell.value) if cell.value else '' for cell in row))
                return
        wb.close()
        update_text('Book not found')

Finally change the command option of find button to call the find_book() function:

find = Button(a, text='Find', command=find_book)


来源:https://stackoverflow.com/questions/54113343/how-to-extract-a-particular-row-value-on-inputting-value-of-a-particular-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!