问题描述
我在右键菜单上有 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()