Search code examples
scrollbarmultilinepysimplegui

Automatically add a scroll in Multiline when the number of rows is exceeded


Tell me how to automatically connect scrolling in PySimpleGUI Multiline when the number of lines entered exceeds. For example, to enable scrolling when there are more than 5 lines

sg.Multiline(size=(42, 5))


Solution

  • The method is to hack the method set for the tk.Scrollbar, and it is only work for the vertical scrollbar for following code.

    import PySimpleGUI as sg
    
    def scrollbar_set(self, lo, hi):
        if float(lo) <= 0.0 and float(hi) >= 1.0:
            self.pack_forget()
        elif self.cget("orient") != sg.tk.HORIZONTAL:
            self.pack(side=sg.tk.RIGHT, fill=sg.tk.Y)
        self.old_set(lo, hi)
    
    sg.tk.Scrollbar.old_set = sg.tk.Scrollbar.set
    sg.tk.Scrollbar.set     = scrollbar_set
    
    layout = [
        [sg.Text('Auto hide scrollbar', size=25)],
        [sg.Multiline(size=(20, 5), expand_x=True, expand_y=True, key='-ML-')]]
    window = sg.Window('Title', layout, finalize=True)
    
    while True:
        event, values = window.read()
    
        if event == sg.WIN_CLOSED:
            break
    
    window.close()