2017-08-26 73 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