首页 文章

搜索tkinter数据帧

提问于
浏览
1

我试图创建的是一个首先创建pandas数据帧的程序 . 然后,它将创建一个带有输入条目框,按钮和文本框的tkinter窗口 . 对于下面的代码,当按下按钮时,我得到一个输出,显示数据框的 Headers 和“搜索”的行 .

import pandas
from tkinter import *
#creates the dataframe
summer17=pandas.read_excel("summer17.xlsx","list")

window = Tk() #start of the main window
#function that will search the dataframe column "company" for any matches
def search_df():
    search_result=summer17[summer17['Company'].str.contains("CAPS")]
    t1.insert(END,search_result)
#Creates the entry box
e1_value=StringVar()
e1=Entry(window)
e1.grid(row=0,column=0)
#Creates a button
b1=Button(window,width=10,text='search',command=search_df)
b1.grid(row=0,column=1)
#Creates a text box
t1=Text(window,height=5,width=80)
t1.grid(row=0,column=2)

window.mainloop() #end of the main window

这样做很好,但是,我希望用户能够在输入框中输入一个值,然后按下按钮并搜索该条目 . 所以我改变了功能

def search_df():
    search_result=summer17[summer17['Company'].str.contains(e1_value.get())]
    t1.insert(END,search_result)

如果我将其留空,则返回整个数据框(正如我可能或不期望的那样) . 但是,如果我将CAPS放入输入框并按下按钮,它仍会返回整个数据帧 .

我的猜测是,当我从输入框中获取值时,有一个变量未命中匹配,但我不确定如何纠正它 .

1 回答

  • 1

    我使用我的一个文件来创建数据帧 .

    您需要使用textvariable参数将e1_value添加到条目中 .

    我在回车键和你的功能之间添加了一个绑定,因此你不必按下按钮,你可以按回车键 . 为此,我使用了bind函数 . 此函数绑定窗口小部件和tkinter事件 . 它执行所选的函数并传递参数(即事件) .

    然而,当它执行所选功能时,小部件按钮 does not pass any parameter 的命令参数(事件始终是左clic) . 's why your function takes *event as a parameter, event can be None. (i used *event but event=None works too, and i don'知道哪种方式是最pythonic的方式,对不起)

    PS:您应该使用 import tkinter as tk ,因为如果您使用 from tkinter import * ,您可能会与变量和函数名称发生冲突

    import pandas
    import tkinter as tk
    #creates the dataframe
    summer17=pandas.read_csv("User_AD_Commun01_2017-07-26_15-01.csv",
                             sep=";",
                             encoding="latin1")
    
    
    
    
    window = tk.Tk() #start of the main window
    #function that will search the dataframe column "company" for any matches
    
    
    def search_df(*event):
        search_result=summer17.loc[summer17['company'].str.contains(e1_value.get(),
                                   na=False, #ignore the cell's value is Nan
                                   case=False)] #case insensitive
        t1.insert(tk.END,search_result)
    
    
    #Creates the entry box and link the e1_value to the variable
    e1_value=tk.StringVar()
    e1=tk.Entry(window, textvariable=e1_value)
    e1.grid(row=0,column=0)
    #execute the search_df function when you hit the "enter" key and put an event
    #parameter
    e1.bind("<Return>", search_df) 
    
    #Creates a button
    b1=tk.Button(window,
                 width=10,
                 text='search',
                 command=search_df)
    
    b1.grid(row=0,column=1)
    
    #Creates a text box
    t1=tk.Text(window,height=5,width=80)
    t1.grid(row=0,column=2)
    
    window.mainloop() #end of the main window
    

相关问题