Search code examples
pythonpython-3.xtkinterscrolltkinter-text

How to prevent the widgets inside text from moving beyond the boundary? Tkinter


I have a Text widget in which there are a stack of widgets inserted as a window. Whenever I scroll, the widgets move beyond the Text boundaries until their end crosses over. Here is a sample code that produces a similar symptom.

from tkinter import *

root = Tk()

inst_frame = Frame(root, highlightthickness = 1, highlightbackground = 'black', bg = 'white')
inst_frame.pack(padx = 10, pady = (0,10), side = 'bottom', anchor = 'w')
lab = Label(inst_frame, text = 'Stack of widgets', bg = 'RoyalBlue', font = ('Roboto', 12), fg = 'white') 
lab.pack(side = 'top', anchor = 'nw', fill = 'x', pady = (0,10))
disp_inst_frame = Frame(inst_frame, bg = 'white')
disp_inst_frame.pack(side = 'bottom', fill = 'both')
inst_text_frame = Frame(disp_inst_frame, width = 820, height = 200, bg = 'white')
inst_text_frame.pack(side = 'left', expand = False, fill = 'x')
inst_text_frame.pack_propagate(False)
inst_text = Text(inst_text_frame, font = ('Roboto', 12), wrap = 'word', bd = 0)
inst_vsb = Scrollbar(disp_inst_frame, command = inst_text.yview)
inst_text.configure(yscrollcommand = inst_vsb.set)
inst_text.pack(padx = 10, pady = (0, 10), fill = 'x')
inst_vsb.pack(side = 'right', fill = 'y', padx = (0, 10), pady = (0, 10))

for _ in range(0, 5): #Inserts blank frames
    sample_frame = Frame(inst_frame, height = 100, width = 500, bg = 'black')
    inst_text.window_create(END, window = sample_frame)
    inst_text.insert(END, '\n'*5)

root.mainloop()

Here one can notice that the sample_frames that were inserted move beyond the bounds when scrolled.

Any help would be greatly appreciated.


Solution

  • Use:

    sample_frame = Frame(inst_text, height = 100, width = 500, bg = 'black') # inst_text instead of inst_frame