Reputation: 729
I was working on an image viewer, but I noticed in the image viewer when the link to be displayed is too long it cuts it off. How can I modify this code So that if the string is too long, it prints it on a new line instead. I was following a guide so you can take a look at https://realpython.com/pysimplegui-python/
# img_viewer.py
import PySimpleGUI as sg
import os.path
# First the window layout in 2 columns
file_list_column = [
[
sg.Text("Image Folder"),
sg.In(size=(25, 1), enable_events=True, key="-FOLDER-"),
sg.FolderBrowse(),
],
[
sg.Listbox(
values=[], enable_events=True, size=(40, 20), key="-FILE LIST-"
)
],
]
# For now will only show the name of the file that was chosen
image_viewer_column = [
[sg.Text("Choose an image from list on left:")],
[sg.Text(size=(40, 1), key="-TOUT-")],
[sg.Image(key="-IMAGE-")],
]
# ----- Full layout -----
layout = [
[
sg.Column(file_list_column),
sg.VSeperator(),
sg.Column(image_viewer_column),
]
]
window = sg.Window("Image Viewer", layout)
# Run the Event Loop
while True:
event, values = window.read()
if event == "Exit" or event == sg.WIN_CLOSED:
break
# Folder name was filled in, make a list of files in the folder
if event == "-FOLDER-":
folder = values["-FOLDER-"]
try:
# Get list of files in folder
file_list = os.listdir(folder)
except:
file_list = []
fnames = [
f
for f in file_list
if os.path.isfile(os.path.join(folder, f))
and f.lower().endswith((".png", ".gif"))
]
window["-FILE LIST-"].update(fnames)
elif event == "-FILE LIST-": # A file was chosen from the listbox
try:
filename = os.path.join(
values["-FOLDER-"], values["-FILE LIST-"][0]
)
window["-TOUT-"].update(filename)
window["-IMAGE-"].update(filename=filename)
except:
pass
window.close()
Upvotes: 2
Views: 4668
Reputation: 13061
To me, it's better to use library textwrap
to fill your text into new text with new line '\n'
before assign to sg.Text
. Set size
to (40, None)
, 40
is the wraplength.
You'll have a nice string as output, could be nicer than a list ;)
Example here:
import textwrap
import PySimpleGUI as sg
sg.theme("DarkBlue3")
sg.set_options(font=("Courier New", 16))
text = (
"The mission of the Python Software Foundation is to promote, protect, "
"and advance the Python programming language, and to support and "
"facilitate the growth of a diverse and international "
"community of Python programmers.")
new_text = textwrap.fill(text, 40)
layout = [
[sg.Text("Line", size=(40, None), key="OUT")],
[sg.Button("Update1"), sg.Button("Update2")],
]
window = sg.Window('Title', layout, finalize=True)
while True:
event, values = window.read()
if event in (sg.WINDOW_CLOSED, "Exit"):
break
elif event == 'Update1':
window['OUT'].update(new_text)
elif event == 'Update2':
window['OUT'].update("Line")
print(event, values)
window.close()
Upvotes: 5