Pysimplegui: [Pregunta] ¿Usar imagen personalizada para FileBrowse / FolderBrowse?

Creado en 16 jul. 2020  ·  5Comentarios  ·  Fuente: PySimpleGUI/PySimpleGUI

Tipo de problemas (mejora, error, error, pregunta)

Pregunta

Sistema operativo

Ubuntu 18.04.4 LTS

Versión de Python

Python 3.6.9

Versión y puerto de PySimpleGUI

<module 'PySimpleGUI' from '$HOME/temp/test/lib/python3.6/site-packages/PySimpleGUI/__init__.py'>

4.24.0 Released 3-Jul-2020

Sus niveles de experiencia en meses o años

Experiencia en programación Python: 4 años.
Experiencia en programación total: 7 años.
¿Ha usado otro marco de interfaz gráfica de usuario de Python (tkinter, Qt, etc.) anteriormente (sí / no está bien)? no.

Ha completado estos pasos:

  • [x] Lea las instrucciones sobre cómo presentar un problema.
  • [x] Buscó su problema en los documentos principales http://www.PySimpleGUI.org .
  • [x] Buscó a través del archivo Léame su puerto específico si no es PySimpleGUI (Qt, WX, Remi)
  • [x] Buscó programas de demostración que sean similares a su objetivo http://www.PySimpleGUI.com
  • [x] Tenga en cuenta que también hay programas de demostración en cada puerto en GitHub
  • [x] Ejecute su programa fuera de su depurador (desde una línea de comando)
  • [x] Buscó a través de problemas (abiertos y cerrados) para ver si ya se informaron
  • [x] Vuelve a intentarlo actualizando tu archivo PySimpleGUI.py para usar el actual en GitHub. Es posible que su problema ya se haya solucionado, pero aún no está en PyPI.

Descripción de la pregunta

¿Es posible utilizar un icono personalizado para FileBrowse o FolderBrowse? He visto que esos dos atajos son solo envoltorios para Button, pensé que podría usar image_data, pero no funcionó.
Creo que puedo imitar la funcionalidad con un botón, ¿verdad?

Pega tu código aquí


Muestra de código

#!/usr/bin/env python3
import PySimpleGUI as sg

sg.theme('LightBlue')   # Add a touch of color
# All the stuff inside your window.
filepng = "iVBORw0KGgoAAAANSUhEUgAAABMAAAAZCAYAAADTyxWqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAAuQAAALkB4qdB6AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAADlSURBVDiN7dW9SkNBEIbhRxO9A0kh/oAgsQ2kVfEqLFLkMmy8DRvrgFjbiWCV5B4CQirtrEQhCbHIHAzHKOeslueDj2WW3Xd2d2AHjjDEFPMC/sAdtq3QsCAk7xF2lkFrcaIarvC4KlvoAi08o4F1POEM42xRlqn7C0hcbY5bnGMS8RgHgp6im0g+wy4esJ8Kgx46Fs+0h+t6AuQY90vxK7ZwUgb2HmMjnNdGGdglXrCZmz/EaRYUreZP6maMvxTgmypYBatg/6a6xW9ZQxtvCYx2jDPSu1PeA2ii76tBlPUk9jc/AameX+bEqOgkAAAAAElFTkSuQmCC"

layout = [
    [sg.Text('Log File')],
    [sg.InputText('output/msf.log', key='inputlog'), sg.FileBrowse(target='inputlog', image_data=filepng)],
    ...
]

# Create the Window
window = sg.Window('AutoAuditor', layout)
# Event Loop to process "events" and get the "values" of the inputs
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'test':   # if user closes window or clicks cancel
        break
    print('You entered ', values[0])

window.close()

Obviamente, obtengo un error:

Traceback (most recent call last):
  File "./gui.py", line 9, in <module>
    [sg.InputText('output/msf.log', key='inputlog'), sg.FileBrowse(target='inputlog', image_data=fa.icons['file'])],
TypeError: FileBrowse() got an unexpected keyword argument 'image_data'

Editar: Mientras tanto, estoy creando el botón FileBrowser de antemano y luego modificando la variable ImageData.

Gracias, herramienta muy útil.

enhancement

Todos 5 comentarios

¿Supongo que quiere usar una imagen en el botón? En ese caso, no es un icono, es una imagen de botón

Como solución alternativa, puede crear su propio botón de búsqueda de archivos con una imagen copiando el código de FileBrowse y agregando la imagen (nombre de archivo o datos) a la llamada del botón.

Aquí está el código FileBrowse

def FileBrowse(button_text='Browse', target=(ThisRow, -1), file_types=(("ALL Files", "*.*"),), initial_folder=None,
               tooltip=None, size=(None, None), auto_size_button=None, button_color=None, change_submits=False,
               enable_events=False, font=None, disabled=False,
               pad=None, key=None, k=None, metadata=None):
    """

    :param button_text: text in the button (Default value = 'Browse')
    :type button_text: (str)
    :param target: key or (row,col) target for the button (Default value = (ThisRow, -1))
    :param file_types: filter file types (Default value = (("ALL Files", "*.*")))
    :type file_types: Tuple[Tuple[str, str], ...]
    :param initial_folder:  starting path for folders and files
    :param tooltip: text, that will appear when mouse hovers over the element
    :type tooltip: (str)
    :param size:  (w,h) w=characters-wide, h=rows-high
    :type size: (int, int)
    :param auto_size_button:  True if button size is determined by button text
    :type auto_size_button: (bool)
    :param button_color: button color (foreground, background)
    :type button_color: Tuple[str, str] or str
    :param change_submits: If True, pressing Enter key submits window (Default = False)
    :type change_submits: (bool)
    :param enable_events: Turns on the element specific events.(Default = False)
    :type enable_events: (bool)
    :param font: specifies the font family, size, etc
    :type font: Union[str, Tuple[str, int]]
    :param disabled: set disable state for element (Default = False)
    :type disabled: (bool)
    :param pad: Amount of padding to put around element in pixels (left/right, top/bottom)
    :type pad: (int, int) or ((int, int),(int,int)) or (int,(int,int)) or  ((int, int),int)
    :param key: key for uniquely identify this element (for window.FindElement)
    :type key: Union[str, int, tuple, object]
    :param k: Same as the Key. You can use either k or key. Which ever is set will be used.
    :type k: Union[str, int, tuple, object]
    :return: returns a button
    :rtype: (Button)
    """
    return Button(button_text=button_text, button_type=BUTTON_TYPE_BROWSE_FILE, target=target, file_types=file_types,
                  initial_folder=initial_folder, tooltip=tooltip, size=size, auto_size_button=auto_size_button,
                  change_submits=change_submits, enable_events=enable_events, disabled=disabled,
                  button_color=button_color, font=font, pad=pad, key=key, k=k, metadata=metadata)

Sí, me refiero a una imagen. Lo usaré, muchas gracias.

Lo único que realmente necesita agregar a su llamada de botón es button_type. Eso es lo que controlará si realiza una búsqueda de archivos, etc.

Y tal vez un par de parámetros que tienen valores predeterminados (tipos de archivo, por ejemplo)

¿Fue útil esta página
0 / 5 - 0 calificaciones

Temas relacionados

thelou1s picture thelou1s  ·  4Comentarios

flowerbug picture flowerbug  ·  4Comentarios

MikeTheWatchGuy picture MikeTheWatchGuy  ·  6Comentarios

OPMUSER picture OPMUSER  ·  5Comentarios

xuguojun168 picture xuguojun168  ·  3Comentarios