Add scrollbar/fix format of output to fit tk window

Question:
How can I either add a scrollbar to allow the user to see the full outputted text, or format the text so that it fits inside my window?

Current behavior:
The text is centered somewhere and gets cut off by the borders.
I tried adding a scrollbar myself but it doesn’t show in the output
Desired behavior
The text is lined up against the left margin and is fully legible.

Repl link:
https://replit.com/@yangqil/CS-IA-3-1?v=1

  # Tkinter widgets needed for scrolling.  The only native scrollable container that Tkinter provides is a canvas.
  # A Frame is needed inside the Canvas so that widgets can be added to the Frame and the Canvas makes it scrollable.
  cTableContainer = tk.Canvas(root)
  fTable = tk.Frame(cTableContainer)
  sbHorizontalScrollBar = tk.Scrollbar(root)
  sbVerticalScrollBar = tk.Scrollbar(root)

  # Updates the scrollable region of the Canvas to encompass all the widgets in the Frame
  def updateScrollRegion():
    cTableContainer.update_idletasks()
    cTableContainer.config(scrollregion=fTable.bbox())

  # Sets up the Canvas, Frame, and scrollbars for scrolling
  def createScrollableContainer():
    cTableContainer.config(xscrollcommand=sbHorizontalScrollBar.set,yscrollcommand=sbVerticalScrollBar.set, highlightthickness=0)
    sbHorizontalScrollBar.config(orient=tk.HORIZONTAL, command=cTableContainer.xview)
    sbVerticalScrollBar.config(orient=tk.VERTICAL, command=cTableContainer.yview)

    sbHorizontalScrollBar.place(x=200,y=200)
    #sbVerticalScrollBar.pack(fill=tk.Y, side=tk.RIGHT, expand=tk.FALSE)
    cTableContainer.place(x=0,y=0)
    cTableContainer.create_window(0, 0, window=fTable, anchor=tk.NW)

The way you are using labels for output won’t allow for scrolling if the content exceeds the window size.
It’s better if you use a text widget along with a scrollbar. You can use the output.insert method to add text to the Text widget. Just remember to clear the existing text in the widget before inserting new text.

Taking an example using your bakery.py:

def GUI():
    root = tk.Tk()
    root.title("Mom's Bakery")
    root.geometry("700x700")

    # You create a Text widget for output
    output = tk.Text(root, wrap='word', height=10, width=50)
    output.place(x=40, y=40)

    # Than, you create a Scrollbar and attach it to the Text widget
    scrollbar = tk.Scrollbar(root, command=output.yview)
    scrollbar.place(x=430, y=40, height=200)
    output.config(yscrollcommand=scrollbar.set)

    # And don't forget to update your eggtart function to use output.insert instead of output.config
    def eggtart():
        #this is after your code inside the eggtart
        output.delete('1.0', tk.END)  # Clear existing text
        output.insert(tk.END, f'Your formatted output text here')
2 Likes

Thanks for your response! I’ll check if this works!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.