So I have this program that grabs a text file from the internet, reads it and then set the decoded text to an element.
import PySimpleGUI as sg
import urllib.request
data = urllib.request.urlopen("link to a text file")
layout = [[sg.Text('', k='textElement')]]
window = sg.window('Foo', layout)
def setText(Text):
for line in Text:
decodedText = line.decode("utf-8")
window['textElement'].update(value=decodedText)
setText(data)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
window.close()
Something like that. But instead it only displays the last line of the text file.
CodePudding user response:
You're decoding every line then calling .update()
on the text element for each line. Instead:
def setText(Text):
decodedText = Text.read().decode("utf-8")
window['textElement'].update(value=decodedText)
You can just read the entire text, decode it and assign that (note that you shouldn't really name functions or variables using capitals, set_text
and decided_text
would be better, and Text
should definitely be text
or something else lowercase)
Or if you have other reasons to do it line by line:
def setText(Text):
Text = ''.join(line for line in Text)
decodedText = Text.decode("utf-8")
window['textElement'].update(value=decodedText)
Note however, that your code seems to assume it's getting bytes
(which would need to be encoded), while it seems to make sense you'd be getting text (i.e. str
), so if you still have issues, you may simple have to skip decoding the already decoded text.
CodePudding user response:
Method update
of Text element will replace full content by new values, so only last update will be shown in following code.
for line in Text:
decodedText = line.decode("utf-8")
window['textElement'].update(value=decodedText)
The content of a txt file maybe large to fit in a fixed-size Text element, then a scrollbar required to view all, so it will be better to use a Multiline element here.
import urllib
import PySimpleGUI as sg
url = 'https://www.python.org/humans.txt'
try:
response = urllib.request.urlopen(url)
if response.code == 200:
text = response.read().decode('utf-8')
else:
text = 'Failed to load following file.\n' url
except urllib.error.HTTPError:
text = 'Failed to load following file.\n' url
font = ('Courier New', 11)
sg.theme('DarkBlue4')
sg.set_options(font=font)
layout = [
[sg.Multiline(text, size=(80, 10), key='Multiline')],
[sg.Push(), sg.Button('Exit')],
]
window = sg.Window('Window Title', layout, finalize=True)
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
window.close()