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

如何解决Python 搜索引擎 GUI(PySimpleGui) - 带有 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',default=True,key='-CONTAINS-'),sg.Radio('StartsWith',key='-STARTSWITH-'),sg.Radio('EndsWith',key='-ENDSWITH-')],[sg.Text('Search Path',sg.Combo(['ShdwProd/','Other/'],readonly=True,size=(38,key='-PATH-',),#display only folder name where files are located such as  'ShadowProd' and 'Ohter' in Combo 
     sg.Button('Search',size=(20,key='-SEARCH-'),sg.Button('Download',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',key='-CONTAINS-',default=True),sg.Radio('StartsWith',key='-STARTSWITH-'),sg.Radio('EndsWith',key='-ENDSWITH-')],[sg.Text('Search Path',sg.Combo(['ShdwProd/','Other/'],default_value='ShdwProd/',readonly=True,size=(38,key='-PATH-',),#display only folder name where files are located such as  'ShadowProd' and 'Ohter' in Combo
     sg.Button('Search',size=(20,key='-SEARCH-'),sg.Button('Download',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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?