I want to create a dynamic screen layout.
Is there a way to determine the width for a string in a specific font?
I want to create a dynamic screen layout.
Is there a way to determine the width for a string in a specific font?
You can use get_size()
to return the width and length of an element in pixels. For more information check the PySimpleGUI documentation.
import PySimpleGUI as sg
my_string = 'Hello World!'
layout = [
[sg.Text(text=my_string, key='-TEXT-', font=('Helvetica', 11))],
[sg.Button('Go')]]
window = sg.Window(title='Name', layout=layout).finalize()
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
if event == 'Go':
# GETTING SIZE OF THE TEXT ELEMENT IN PIXELS
size_of_text = window['-TEXT-'].get_size()
print('Width:', size_of_text[0], 'pixels')
print('Height:', size_of_text[1], 'pixels')
window.close()