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

Posted

技术标签:

【中文标题】Python 搜索引擎 GUI(PySimpleGui) - 带有 right_click_menu 的列表框【英文标题】:Python search engine GUI(PySimpleGui) - Listbox with right_click_menu 【发布时间】:2021-10-05 06:54:34 【问题描述】:

我在右键菜单上有 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")

(*) 标记是我不确定的,并且有错误。

【问题讨论】:

这是什么错误 【参考方案1】:

代码修改如下

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

【讨论】:

以上是关于Python 搜索引擎 GUI(PySimpleGui) - 带有 right_click_menu 的列表框的主要内容,如果未能解决你的问题,请参考以下文章

从另一个 Python 进程更新 Python GUI

python学习日记-百度翻译GUI

Python3.5、Win32gui、Tkinter。我无法从屏幕获取 Pixel

python win32api win32gui win32con 窗口句柄 发送消息 常用方法 键盘输入

Python实战爬取豆瓣排行榜电影数据(含GUI界面版)

如何使用 pkexec 执行 Python 脚本