Home > Software design >  Making a tkinter horizontal scroll bar with grid python
Making a tkinter horizontal scroll bar with grid python

Time:10-05

So im having trouble making a horizontal scroll bar with grid and have been trying to mix and match different parameters and such and I've hit a rock with this tutorial https://newbedev.com/tkinter-canvas-scrollbar-with-grid being the first example this is my code so far

window = tk.Tk()
window.geometry("1200x600")

frame_main = tk.Frame(window, bg="gray")
frame_main.grid(sticky='news')


# Create a frame for the canvas with non-zero row&column weights
frame_canvas = tk.Frame(frame_main)
frame_canvas.grid(row=0, column=0, pady=(5, 0), sticky='nw')
frame_canvas.grid_rowconfigure(0, weight=1)
frame_canvas.grid_columnconfigure(0, weight=1)

# Add a canvas in that frame
canvas = tk.Canvas(frame_canvas, bg="yellow")
canvas.grid(row=2, column=2, sticky="news")

# Link a scrollbar to the canvas
vsb = tk.Scrollbar(window, orient="horizontal", command=canvas.xview)
vsb.grid(row=0, column=2, sticky='we')
canvas.configure(xscrollcommand=vsb.set)



frame_canvas.config(width=first5columns_width   vsb.winfo_width(),height=first5rows_height)

canvas.config(scrollregion=canvas.bbox("all"))






col_0_head = tk.Label(window, text = " Adventures_Sherlock_Holmes.txt ", pady = 20) # pady = 20 gives some vertical
# separation between this row and the next
col_0_head.grid(row = 0, column = 0)
col_1_head = tk.Label(window, text = " Age_Innocence.txt ")
col_1_head.grid(row = 0, column = 1)
col_2_head = tk.Label(window, text = " Alice_Wonderland.txt ")
col_2_head.grid(row = 0, column = 2)




window.mainloop()

CodePudding user response:

If you want to create a scroll bar in tkitner using grid option, you can simply create a scrollframe and pack the scrollbar in that frame

This is the type of code you can write:

scrollframe = Frame(root)
scrollframe.grid(...)

scrollx = Scrollbar(scrollframe, orient=HORIZONTAL)
scrollx.pack(expand=1, fill=X, side=BOTTOM)

This should ideally work if you don't want the scrollbar to fill your entire GUI Bottom X-axis. In case you are ok with it filling the entire GUI, then just pack the scrollbar in your root or Tk widget.

Thank You!

CodePudding user response:

Two problems in your code.

The first is no scrollregion in canvas.

The second is wrong grid row and column values.

Here's a code snippet that solves your problem.

# Add a canvas in that frame
canvas = tk.Canvas(frame_canvas, bg="yellow", scrollregion = "0 0 2000 2000")
canvas.grid(row=2, column=2, sticky="news")

# Link a scrollbar to the canvas
vsb = tk.Scrollbar(window, orient="horizontal", command=canvas.xview)
vsb.grid(row=1, column=0, sticky='ew')
canvas.configure(xscrollcommand=vsb.set)
  • Related