pythonuser-interfacepysimplegui

PySimpleGUI: How to detect overflow of elements beyond the window limits?


In the example below, there is a row with more elements than fit the window. How can I detect the overflow?

import PySimpleGUI as sg

layout = [[sg.Text(f"word{i}") for i in range(30)]]
window = sg.Window("Demo", layout, size=(500, 100))
window.finalize()

while True:
  event, values = window.read()
  if event == sg.WINDOW_CLOSED:
    break

Solution

  • The size of Text element will be different for different font and different-length text.

    import PySimpleGUI as sg
    
    font = ("Courier New", 10)
    sg.set_options(font=font)
    
    layout = [[sg.Text(f"word{i}", key=f"TEXT {i}") for i in (0, 10)]]
    window = sg.Window("Demo", layout, size=(500, 100), finalize=True)
    window.refresh()
    text0 = window['TEXT 0'].widget
    w0, h0 = text0.winfo_width(), text0.winfo_height()
    text10 = window['TEXT 10'].widget
    w10, h10 = text10.winfo_width(), text10.winfo_height()
    print(w0, h0, w10, h10)
    
    while True:
      event, values = window.read()
      if event == sg.WINDOW_CLOSED:
        break
    
    window.close()
    
    44 20 52 20
    

    Monospace font ('Courier New', 10) used here, and we can get the basic widths/heights for 4-char and 5-char Texts by above code, they are 44/20 and 52/20.

    There are 10 4-char Texts and 20 5-char Texts in your code, also default padding (5, 3) and window default margins (10, 5).

    If nothing wrong, you can calculate it as following: