I wanted to try to use tkinter for the first time, and had a little program I wanted to try.
It needed some text in a "table" and because of the number of rows and columns, I needed scrollbars for vertical and horizontal scrolling.
I took two examples from https://pythonguides.com/python-tkinter-scrollbar/ and tried to combine the two to get effectively the first example, with more columns and a horizontal scrollbar.
It works perfectly, except that the horizontal scrollbar doesn't extend across the whole of the bottom of the canvas, but is fixed in the bottom right.
I cannot figure out what I have done wrong, but any guidance would be most appreciated.
#!/usr/bin/python3
import tkinter as tk
root = tk.Tk()
root.title("Customer Data")
# Create a canvas and scrollbar
canvas = tk.Canvas(root)
vertScrollbar = tk.Scrollbar(root, orient=tk.VERTICAL, command=canvas.yview)
horzScrollbar = tk.Scrollbar(root, orient=tk.HORIZONTAL, command=canvas.xview)
# canvas.configure(yscrollcommand=vertScrollbar.set, xscrollcommand=horzScrollbar.set)
#############
canvas.config(
xscrollcommand=horzScrollbar.set,
yscrollcommand=vertScrollbar.set
)
#############
# Create a frame inside the canvas
frame = tk.Frame(canvas)
canvas.create_window((0, 0), window=frame, anchor='nw')
# Add table headers
headers = ['Name', 'Email', 'Phone', 'Location', 'Animal']
for col, header in enumerate(headers):
tk.Label(frame, text=header, font=('Arial', 12, 'bold')).grid(row=0, column=col, padx=10, pady=5)
# Add customer data to the table
customers = [
('John Doe' , 'john@example.com', '(123) 456-7890', 'Williamstown, Washington', 'Elephant'),
('Jane Smith', 'jane@example.com', '(987) 654-3210', 'Williamstown, Washington', 'Elephant'),
('Jane Smith', 'jane@example.com', '(987) 654-3211', 'Williamstown, Washington', 'Elephant'),
('Jane Smith', 'jane@example.com', '(987) 654-3212', 'Williamstown, Washington', 'Elephant'),
('Jane Smith', 'jane@example.com', '(987) 654-3213', 'Williamstown, Washington', 'Elephant'),
# Add more customer data here
]
for row, customer in enumerate(customers, start=1):
for col, item in enumerate(customer):
tk.Label(frame, text=item).grid(row=row, column=col, padx=10, pady=5)
# Update the scroll region
frame.update_idletasks()
canvas.configure(scrollregion=canvas.bbox('all'))
canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
vertScrollbar.pack(side=tk.RIGHT, fill=tk.Y)
horzScrollbar.pack(side=tk.BOTTOM, fill=tk.X)
root.mainloop()