簡體   English   中英

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

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

我在右鍵單擊菜單上有 OPEN 和 SAVE 選項,它使用戶能夠使用 PySimpleGui 在 ListBox 輸出中打開或保存選定的多個文件。我在觸發這些事件時遇到錯誤。你能幫忙嗎? 請參考下面我編寫但有錯誤的代碼。

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")

(*) 標記是我不確定的並且有錯誤來自..

代碼修改如下

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