简体   繁体   English

Python 搜索引擎 GUI(PySimpleGui) - 带有 right_click_menu 的列表框

[英]Python search engine GUI(PySimpleGui) - Listbox with right_click_menu

I have OPEN and SAVE options on the right click menu which enables users to open or save selected multiple files in the ListBox output using PySimpleGui.. I am having errors to trigger those events.. Can you please help?我在右键单击菜单上有 OPEN 和 SAVE 选项,它使用户能够使用 PySimpleGui 在 ListBox 输出中打开或保存选定的多个文件。我在触发这些事件时遇到错误。你能帮忙吗? Please refer to the code below I scripted but having errors.请参考下面我编写但有错误的代码。

import PySimpleGUI as sg
from tkinter.filedialog import asksaveasfile
from tkinter import *
import os
import threading
from time import sleep
from random import randint

def search(values, window):
    """Perform a search based on term and type"""
    os.chdir('G:\MOTOR\DataExtracts/')
    global results
    # reset the results list
    results.clear() 
    results = []
    matches = 0 # count of records matched
    records = 0 # count of records searched
    window['-RESULTS-'].update(values=results)
    window['-INFO-'].update(value='Searching for matches...')

    # search for term and save new results
    for root, _, files in os.walk(values['-PATH-']):
        for file in files:
            records +=1
            if values['-ENDSWITH-'] and file.lower().endswith(values['-TERM-'].lower()):
                results.append(f'{file}')
                window['-RESULTS-'].update(results)
            if values['-STARTSWITH-'] and file.lower().startswith(values['-TERM-'].lower()):
                results.append(f'{file}')
                window['-RESULTS-'].update(results)
            if values['-CONTAINS-'] and values['-TERM-'].lower() in file.lower():
                results.append(f'{file}')
                window['-RESULTS-'].update(results)
                
                matches += 1
                
    window['-INFO-'].update('Enter a search term and press `Search`')
    sg.PopupOK('Finished!') # print count of records of matched and searched in the popup(*)

def open_file(file_name):
    # probably should add error handling here for when a default program cannot be found.(*)
    # open selected files with read-only mode (check box or right click option)(*)
    pass

def save_file(file_name):
        # download selected files - one file or multiple files download at the same time (*)
        # print downloading time or progress bar with downloaded files(*)
        # print downloaded files logging info(*)
# create the main file search window
results = []
sg.change_look_and_feel('Black')
command = ['Open', 'Save']
cmd_layout = [[sg.Button(cmd, size=(10, 1))] for cmd in command]
layout = [
    [sg.Text('Search Term', size=(11, 1)), sg.Input('', size=(40, 1), key='-TERM-'), 
     sg.Radio('Contains', group_id='search_type', size=(10, 1), default=True, key='-CONTAINS-'),
     sg.Radio('StartsWith', group_id='search_type', size=(10, 1), key='-STARTSWITH-'),
     sg.Radio('EndsWith', group_id='search_type', size=(10, 1), key='-ENDSWITH-')],
    [sg.Text('Search Path', size=(11, 1)), sg.Combo(['ShdwProd/','Other/'],readonly=True, size=(38, 1), key='-PATH-', ), #display only folder name where files are located such as  'ShadowProd' and 'Ohter' in Combo 
     sg.Button('Search', size=(20, 1), key='-SEARCH-'),
     sg.Button('Download', size=(20, 1), key='-DOWNLOAD-')],
    [sg.Text('Enter a search term and press `Search`', key='-INFO-')],
    [sg.Listbox(values=results, size=(100, 28), bind_return_key = True, enable_events=True, key='-RESULTS-', right_click_menu=['&Right', command])],
    [sg.Help(key='-HELP-')]]
window = sg.Window('File Search Engine', layout=layout, finalize=True, return_keyboard_events=True)
window['-RESULTS-'].Widget.config(selectmode = sg.LISTBOX_SELECT_MODE_EXTENDED)
window['-RESULTS-'].expand(expand_x=True, expand_y=True)



  # main event loop
    while True:
        event, values = window.read()
        if event is None:
            break
        if event == '-SEARCH-':
            search(values, window)
        if event == '-RESULTS-' and len(values['-RESULTS-']):
            
            if event == '-OPEN-':  # need to code(*)
                pass
            if event == '-DOWNLOAD-': # need to code(*)
                 pass       
        if event == '-HELP-':
            sg.Popup("My help message")

the (*) marks are what I am not sure about and having errors from.. (*) 标记是我不确定的并且有错误来自..

Code revised as following代码修改如下

import os
import threading
from time import sleep
from random import randint

import PySimpleGUI as sg


def search(values, window):
    """Perform a search based on term and type"""
    os.chdir("G:/MOTOR/DataExtracts/")
    global results
    # reset the results list
    results = []
    matches = 0 # count of records matched
    records = 0 # count of records searched
    window['-RESULTS-'].update(values=results)
    window['-INFO-'].update(value='Searching for matches...')
    window.refresh()

    # search for term and save new results
    for root, _, files in os.walk(values['-PATH-']):    # path information of file missed here
        for file in files:
            records +=1
            if any([values['-ENDSWITH-']   and file.lower().endswith(values['-TERM-'].lower()),
                    values['-STARTSWITH-'] and file.lower().startswith(values['-TERM-'].lower()),
                    values['-CONTAINS-']   and values['-TERM-'].lower() in file.lower()]):
                results.append(f'{file}')

                matches += 1
    window['-RESULTS-'].update(results)
    window['-INFO-'].update('Enter a search term and press `Search`')
    window.refresh()
    sg.PopupOK('Finished!') # print count of records of matched and searched in the popup(*)

def open_files(filenames):
    """
    probably should add error handling here for when a default program cannot be found.(*)
    open selected files with read-only mode (check box or right click option)(*)
    """

def save_files(filenames):
    """
    download selected files - one file or multiple files download at the same time (*)
    print downloading time or progress bar with downloaded files(*)
    print downloaded files logging info(*)
    """

# create the main file search window
results = []
sg.theme('Black')

command = ['Open', 'Save']
cmd_layout = [[sg.Button(cmd, size=(10, 1))] for cmd in command]

layout = [
    [sg.Text('Search Term', size=(11, 1)),
     sg.Input('', size=(40, 1), key='-TERM-'),
     sg.Radio('Contains',   group_id='search_type', size=(10, 1), key='-CONTAINS-', default=True),
     sg.Radio('StartsWith', group_id='search_type', size=(10, 1), key='-STARTSWITH-'),
     sg.Radio('EndsWith',   group_id='search_type', size=(10, 1), key='-ENDSWITH-')],
    [sg.Text('Search Path', size=(11, 1)),
     sg.Combo(['ShdwProd/','Other/'], default_value='ShdwProd/', readonly=True, size=(38, 1), key='-PATH-', ), #display only folder name where files are located such as  'ShadowProd' and 'Ohter' in Combo
     sg.Button('Search', size=(20, 1), key='-SEARCH-'),
     sg.Button('Download', size=(20, 1), key='-DOWNLOAD-')],
    [sg.Text('Enter a search term and press `Search`', key='-INFO-')],
    [sg.Listbox(values=results, size=(100, 28), select_mode=sg.LISTBOX_SELECT_MODE_EXTENDED, bind_return_key = True, enable_events=True, key='-RESULTS-', right_click_menu=['&Right', command], expand_x=True, expand_y=True)],
    [sg.Help(key='-HELP-')]]

window = sg.Window('File Search Engine', layout=layout, finalize=True, return_keyboard_events=True)

# main event loop
while True:
    event, values = window.read()
    print(event, values)
    if event == sg.WINDOW_CLOSED:
        break
    elif event == '-SEARCH-':
        search(values, window)
    elif event == '-RESULTS-' and len(values['-RESULTS-']):
        pass
    elif event == 'Open':  # need to code(*)
        open(values['-RESULTS-'])
    elif event == 'Save':  # need to code(*)
        save(values['-RESULTS-'])
    elif event == '-DOWNLOAD-': # need to code(*)
        print(values['-RESULTS-'])
    elif event == '-HELP-':
        sg.Popup("My help message")

window.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM