Skip to content Skip to sidebar Skip to footer

Trouble With Scrollbar For Text Widget

I am simply trying to make a scrollbar for the list of checkbuttons that appear on my text widget. So far the scrollbar appears in the correction location and the correct size but

Solution 1:

There are a couple things wrong with your code.

The first thing I would change is to stop trying to dynamically generate variable names. That is virtually never a good idea, and only serves to make your code extremely hard to understand and debug.

Instead, store the checkbuttons and variables in a list or dictionary. There's no requirement that each checkbutton or variable have a distinct variable associated with it.

For example, the following code illustrates how to create a bunch of checkbuttons and variables in a loop:

for i in range(15):
    label = "Robot Test File {}".format(i)
    var = tk.BooleanVar()
    checkbutton = tk.Checkbutton(text, text=label, variable=var)
    cb_vars.append(var)
    checkbuttons.append(checkbutton)

With that, you can now reference the checkbuttons and their variables as you would with any list: cb_vars[0].get(), etc. If you prefer to be able to refer to them by name then you can use a dictionary instead of a list:

cb_vars = {}
checkbuttons = []
for i in range(15):
    label = "Robot Test File {}".format(i)
    var = tk.BooleanVar()
    checkbutton = tk.Checkbutton(text, text=label, variable=var)
    cb_vars[label] = var
    checkbuttons.append(checkbutton)

    text.window_create("insert", window=checkbutton)
    text.insert("end", "\n")

With the above, you can do cb_vars['Robot Test File 1'].get() to get the value of checkbutton number 1. You can of course use anything you want as the index.

Second, the text widget can't scroll things added to the widget with pack, place, or grid. The widget can only scroll things added as content to the widget. To add a checkbutton you can use the window_create method. Assuming you want each checkbutton on a separate line, you'll need to add a newline after each checkbutton.

For example, here's how you could create 15 checkboxes in a scrollable text widget:

import tkinter as tk

root = tk.Tk()

text = tk.Text(root, height=5)
vsb = tk.Scrollbar(root, orient="vertical", command=text.yview)
text.configure(yscrollcommand=vsb.set)
vsb.pack(side="right", fill="y")
text.pack(side="left", fill="both", expand=True)

cb_vars = []
checkbuttons = []
for i in range(15):
    label = "Robot Test File {}".format(i)
    var = tk.BooleanVar()
    checkbutton = tk.Checkbutton(text, text=label, variable=var)
    var.set(False)

    text.window_create("insert", window=checkbutton)
    text.insert("end", "\n")
    cb_vars.append(var)
    checkbuttons.append(checkbutton)

root.mainloop()

Post a Comment for "Trouble With Scrollbar For Text Widget"