Я пытаюсь создать графический интерфейс, который принимает корневой каталог и ключевые фразы в качестве входных данных от пользователя, и выводит все строки в этом каталоге, который содержит ключевые фразы, которые вводит пользователь.Моя функция python работает сама по себе, когда я вручную ввожу параметры, но когда я пытаюсь связать ее с моим макетом TKinter и передать переменные с помощью функции get из пользовательского ввода, в результате я получаю «None».Я относительно новичок в Python, большое спасибо за вашу помощь!
Мой макет TKinter
from myFunction import myFunction
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class Feedback:
def __init__(self, master):
master.title('My Python Function')
master.resizable(False, False)
master.configure(background = '#ffffff')
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
self.style = ttk.Style()
self.style.configure('TFrame', background = '#ffffff')
self.style.configure('TButton', background = '#ffffff')
self.style.configure('TLabel', background = '#ffffff', font = ('Arial', 11))
ttk.Label(self.frame_header, wraplength = 300, text = "Output the desired lines from the directory by entering the following.").grid(row = 0, column = 1)
self.frame_content = ttk.Frame(master)
self.frame_content.pack()
ttk.Label(self.frame_content, text = 'Root Directory:').grid(row = 0, column = 0, pady = 4)
ttk.Label(self.frame_content, text = 'Key Phrases:').grid(row = 2, column = 0)
self.entry_rootdirectory = ttk.Entry(self.frame_content, width = 35, font = ('Arial', 10))
self.text_keyphrases = Text(self.frame_content, width = 35, height = 5, font = ('Arial', 10))
self.entry_rootdirectory.grid(row = 0, column = 1)
self.text_keyphrases.grid(row = 2, column = 1)
ttk.Button(self.frame_content, text = 'Submit', command = self.submit).grid(row = 5, column = 0, pady = 5)
ttk.Button(self.frame_content, text = 'Clear', command = self.clear).grid(row = 5, column = 1, pady = 5)
def submit(self):
#My code that attents to bind to the python script
print(versionFilter(self.entry_rootdirectory.get(), self.text_keyphrases.get(1.0, 'end'))) #trying to get the users input and pass them as parameters for the function, and print out the results afterwards
self.clear()
messagebox.showinfo(title = "Search Requested", message = "Search Submitted!")
def clear(self):
self.entry_rootdirectory.delete(0, 'end')
#self.text_filetypes.delete(1.0, 'end')
self.text_keyphrases.delete(1.0, 'end')
def main():
root = Tk()
feedback = Feedback(root)
root.mainloop()
if __name__ == "__main__": main()
Моя функция Python
import os
def myFunction(rootdir, keyPhrases):
path = r"rootdir" #The root directory being passed as a parameter, this is where the key phrases are being searched from
key_phrases = ["keyPhrases"] #Passed as a parameter, this is the key phrases users input to find corresponding lines in the directory that contains the key phrases
# This for loop allows all sub directories and files to be searched
for (path, subdirs, files) in os.walk(path):
files = [f for f in os.listdir(path) if f.endswith('.txt') or f.endswith('.log')] # Specify here the format of files you hope to search from (ex: ".txt" or ".log")
files.sort() # file is sorted list
files = [os.path.join(path, name) for name in files] # Joins the path and the name, so the files can be opened and scanned by the open() function
# The following for loop searches all files with the selected format
for filename in files:
# Opens the individual files and to read their lines
with open(filename) as f:
f = f.readlines()
# The following loop scans for the key phrases entered by the user in every line of the files searched, and stores the lines that match into the "important" array
for line in f:
for phrase in key_phrases:
if phrase in line:
return print(line)
break
# Prints the selected lines after searching the desired files of the entire directory