I am fairly new to Tkinter and am trying to build an application that contains table data within a scrollable canvas. I have designed a Table class that contains a Canvas widget, which in turn contains a Frame that contains the table content.
However, when trying to make the Canvas scroll-able, I am running into an issue. I have bound the table content's Configure event to a callback that sets the scroll region. However, when I run my application this callback is called forever in an infinite loop, and I am not sure why. I cannot figure out why the Configure event would be constantly firing.
Moreover, when trying to switch between tabs, my app will freeze, presumably because of the app being stuck in a loop of callback calls.
Below is a simplified example of what I am trying to do in my app. Can anyone help me figure out how to fix this problem, while also allowing the table content to be scroll-able?
import tkinter as tk
from tkinter import ttk
class Table(ttk.Frame):
def __init__(self, parent):
ttk.Frame.__init__(self, parent)
self.table_canvas = tk.Canvas(self, bg='cyan')
table_scrollbar = ttk.Scrollbar(
self.table_canvas,
orient='vertical',
command=self.table_canvas.yview)
self.table_content = ttk.Frame(self.table_canvas)
self.table_content.bind('<Configure>', self.on_configure)
self.table_canvas.create_window(
(0, 0),
window=self.table_content,
anchor='nw')
self.table_canvas.configure(yscrollcommand=table_scrollbar.set)
for _ in range(10):
table_row = ttk.Frame(self.table_content)
ttk.Label(
table_row,
text='left text'
).grid(column=0, row=0, sticky='w')
ttk.Label(
table_row,
text='right text'
).grid(column=1, row=0, sticky='e')
table_row.columnconfigure(0, weight=1, uniform='same')
table_row.columnconfigure(1, weight=1, uniform='same')
table_row.pack(fill='x')
self.table_canvas.pack(side='left', fill='both', expand=True)
table_scrollbar.pack(side='right', fill='y')
def on_configure(self, event):
print('on configure triggered')
self.table_canvas.configure(scrollregion=self.table_canvas.bbox('all'))
app = tk.Tk()
app.geometry('600x600')
notebook = ttk.Notebook(app)
tab1 = ttk.Frame(notebook)
tab2 = ttk.Frame(notebook)
container1 = ttk.Frame(tab1)
label_container1 = ttk.Frame(container1)
ttk.Label(label_container1, text='Tab One').pack(side='left')
label_container1.pack(fill='x')
table1 = Table(container1)
table1.pack(fill='both', expand=True)
container1.pack(fill='both', expand=True)
container2 = ttk.Frame(tab2)
label_container2 = ttk.Frame(container2)
ttk.Label(label_container2, text='Tab Two').pack(side='left')
label_container2.pack(fill='x')
table2 = Table(container2)
table2.pack(fill='both', expand=True)
container2.pack(fill='both', expand=True)
notebook.add(tab1, text='One')
notebook.add(tab2, text='Two')
notebook.pack(fill='both', expand=True)
app.mainloop()