Я новичок в питоне. и я пытаюсь создать небольшое приложение с графическим интерфейсом, используя Tkinter в python3. Функциональность, которую я хочу достичь, заключается в том, что
1) программа должна создать небольшое окно, которое принимает строку поиска от пользователя.
введите описание изображения здесь
2) как только пользователь вводит строку и нажимает кнопку поиска, программа должна извлечь данные из таблицы Excel и отобразить результаты в таблице Tkinter (модуль таблицы pandas).
Я написал код отдельно для обеих этих функций и не могу собрать их вместе
вот код для достижения функциональности 1.
from tkinter import *
from pandastable import Table, TableModel
import pandas as pd
# Instance of class tkinter Tk
root = Tk()
# Icon for the window
root.iconbitmap('D:/icon.ico')
# Window Title
root.title('Tri2Find')
df_in = pd.read_excel('D:/tmp/data.xlsx',index_col = None)
# Input variable for entry string
entry_search_string = StringVar()
# Text Field for search string
entry_search = Entry(root, width = 50,textvariable =
entry_search_string).grid(row = 0, column = 1)
# Function for different actions of [GO SEARCH!!] Button
def button_entry_search():
search_string = entry_search_string.get()
# Create a label when button is clicked and print the search term in the label
label_entry_search = Label(root, text = "SEARCHING : "+search_string ).grid(row = 0, column = 2)
# Creating a list for holding the index values
index = []
# Iterating over each row of the data frame
for i in range(len(df_in.index)):
# Converting each row of a data frame into a pandas series
row = pd.Series(df_in.iloc[i,:])
# Check for the user's search token in each row
pattern_boolean = row.str.contains(search_string, case = False, na = False)
# If presence of token is true
if pattern_boolean.any() == True:
# Then append the value of i to the index
index.append(i) # Index contains the row indicies with the required search term
# Data frame which contains the rows with required search term
df_out = df_in.iloc[index,:]
print(df_out)
# [GO SEARCH!!] Button of search term
button_search = Button(root,text = "GO SEARCH!!", width = 13,command =
button_entry_search).grid(row = 0)
# loop function to Run and keep the GUI open
root.mainloop()
Приведенный выше код принимает строку и выводит результаты на консоль, но не в таблицу tkinter
Вот код для функциональности 2.
from tkinter import *
from pandastable import Table, TableModel
import pandas as pd
# Reading the excel from local path
df_in = pd.read_excel('D:/tmp/data.xlsx',index_col = None)
# Reading user input from console
search_token = input("Please Enter the search term :")
# Print a status message
print("Showing results for..." +str(search_token))
# Creating a list for holding the index values
index = []
# Iterating over each row of the data frame
for i in range(len(df_in.index)):
# Converting each row of a data frame into a pandas series
row = pd.Series(df_in.iloc[i,:])
# Check for the user's search token in each row
pattern_boolean = row.str.contains(search_token, case = False, na = False)
# If presence of token is true
if pattern_boolean.any() == True:
# Then append the value of i to the index
index.append(i) # Index contains the row indicies with the required search term
# Data frame which contains the rows with required search term
df_out = df_in.iloc[index,:]
class results_table(Frame):
def __init__(self, parent=None):
self.parent = parent
Frame.__init__(self)
self.main = self.master
self.main.geometry('600x400+200+100')
self.main.iconbitmap('D:/icon.ico')
self.main.title('Tri2Find')
f = Frame(self.main)
f.pack(fill=BOTH,expand=1)
self.table=Table(f, dataframe=df_out,showtoolbar=True, showstatusbar=True)
self.table.show()
return
app = results_table()
#launch the app
app.mainloop()
Приведенный выше код принимает данные с консоли, но выводит их в таблицу Tkinter.
Мне нужна помощь, чтобы объединить эти 2 фрагмента кода в один файл.
- Пользователь вводит строку поиска и нажимает кнопку поиска
- Тогда полученные данные должны появиться в таблице.
Я предполагаю, что ошибка связана с менеджером геометрии, потому что я пытаюсь использовать типы pack () и grid () в одном экземпляре. Но я действительно не знаю, как поместить эти 2 фрагмента кода без каких-либо конфликтов и добиться функциональности. Я новичок в концепции ООП Python тоже.
Заранее спасибо.