python - PySimpleGUI,如何让字符串在新行上打印而不是切断它?
问题描述
我正在使用图像查看器,但我在图像查看器中注意到,当要显示的链接太长时,它会切断它。如何修改此代码以便如果字符串太长,它会在新行上打印它。我正在按照指南进行操作,因此您可以查看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()
解决方案
您可以使用库在分配给之前textwrap
使用新行将文本包装成新文本。设置为,是包裹长度。'\n'
sg.Text
size
(40, None)
40
最好将 size 的高度设置为指定的数字,否则您的窗口将被调整为sg.Text
.
这里的例子:
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 facili"
"tate the growth of a diverse and international community of Python pro"
"grammers.")
new_text = textwrap.wrap(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()
推荐阅读
- c++ - 你如何在 C++ 中执行“while(choice not in operation)”
- java - JAVAFX CheckBox 线程
- css - 媒体查询和 vuejs
- c - `"apue.h"`不是全局环境 PATH ,但程序可以检索它
- node.js - 支付成功后如何跳转到外部网页?
- python-2.7 - 如何选择两个不同列的随机日期时间?
- c++ - 如何使用两个不同的参数值调用我的模拟方法两次
- python - How to sum certain numbers in a python list?
- c++ - 如何使函数模板成为测试的参数?
- javascript - 触发 window.open 作为 ajax 完成