2017-08-26 72 views
1

我试图创建的是一个程序,它将首先创建一个熊猫数据框。然后,它将创建一个tkinter窗口,其中包含一个输入框,一个按钮和一个文本框。对于下面的代码,当按下按钮时,我得到一个输出,显示数据框的标题和“搜索”的行。搜索tkinter数据帧

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

我用我的一个文件来创建数据框。

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

我在回车键和你的功能之间增加了一个绑定,因此你不必按下按钮,而是可以按下回车键。要做到这一点,我使用了绑定功能。这个函数绑定一个小部件和一个tkinter事件。它执行所选的功能并传递一个参数(这是事件)。

但是,窗口小部件按钮的命令参数在执行所选功能时(该事件始终是左键)并不传递任何参数。这就是为什么你的函数将* event作为参数,event可以是None。 (我使用*事件,但事件=无效,我不知道哪种方式是最pythonic的方式,对不起)

PS:你应该使用import tkinter as tk,因为你可能与变量和函数名称有冲突if您使用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 
+0

当心我colunm的名字是公司和你的列名是公司 –

+1

这是梦幻般的,我绝不会想到添加*事件。我想这就是你自学计算机语言所得到的结果。此外,感谢您添加功能,只是推入输入,并案例=假。这些是我想添加的一些功能,但在优先级列表中较低。 – jon