Grid fill empty space in scrollable area tkinter - python-3.x

I'm buildinging a gui with a list of labels in a scrollable area. Now I want that the labels fill the empty space via grid manager. So I use the columnconfigure(0, weight=1) and rowconfigure(0, weight=1) method. It works fine for the scrollbar but not for the labels inside the scrollable area. Example showing my issue:
class app():
def __init__(self):
self.root = tk.Tk()
self.root.geometry("341x448")
self.root.minsize(340,440)
self.root.rowconfigure(0, weight=1)
self.root.columnconfigure(0, weight=1)
def display(self):
self.container = ttk.Frame(self.root)
self.container.rowconfigure(0, weight=1)
self.container.columnconfigure(0, weight=1)
self.canvas = tk.Canvas(self.container)
scrollbar = ttk.Scrollbar(self.container, orient = tk.VERTICAL, command = self.canvas.yview)
self.scrollable_frame = ttk.Frame(self.canvas)
self.scrollable_frame.bind(
"<Configure>",
lambda e: self.canvas.configure(
scrollregion=self.canvas.bbox("all")))
self.canvas.create_window((0, 0), window = self.scrollable_frame, anchor = "nw")
self.canvas.configure(yscrollcommand = scrollbar.set)
for i in range(15):
Label = ttk.LabelFrame(self.scrollable_frame, text = "Sample scrolling label")
Label.grid(row = i, column = 0, columnspan=2, sticky=tk.NSEW)
Label.columnconfigure(0, weight=1)
Button = ttk.Button(Label, text=f"Button {i}")
Button.grid(row=0, column=0, sticky=tk.NW)
self.container.grid(row = 0, column = 0, sticky = "nswe")
self.canvas.grid(row = 0, column = 0, sticky = 'nswe')
scrollbar.grid(row = 0, column = 2, sticky = "ns")
self.root.mainloop()
if __name__ =="__main__":
start = app()
start.display()

There are a couple of reasons why your labels do not fill the horizontal space:
You grid the labels in self.scrollable_frame but you have not configured its grid to expand. You need to add
self.scrollable_frame.columnconfigure(0, weight=1)
You have not set the width and height of self.scrollable_frame when you put it in the canvas, so by default, it stays the size it needs to display all its content. If you want it to expand to fill all the space available in the canvas, you can bind the canvas resizing event to a function that will resize the frame accordingly. So add
self.canvas.bind("<Configure>", self.resize)
in self.display() and create the self.resize() function
def resize(self, event):
w = self.scrollable_frame.winfo_reqwidth()
h = self.scrollable_frame.winfo_reqheight()
self.canvas.itemconfigure(1, width=max(w, event.width), height=max(h, event.height))
that makes the frame expand if the canvas is larger than the minimum size required to display all the widgets.
By the way, I suggest you to follow PEP 8 style guide, especially for names, e.g. capitalize class names but not variable names. And above all, be consistent, it will make the code clearer and easier to understand. In particular, I find using Label and Button as variable names quite confusing as they are class names in tkinter.

Related

Tkinter Canvas scroll slow rendering

The canvas Widget in Tkinter is very slow at drawing, causing a lot of distortion to the applications visuals when scrolling even when using limited widgets.
I have had a search around but only seem to have answers from people drawing multiple things to a canvas rather than the scrollbar effects.
Is there any issues with my code that would cause this issue or are there any methods to fix the draw times to be more visually smooth. In the application this is meant for each row is a different colour which can make it extremely ugly to look at and hard to find the data the user is looking for.
MVCE:
#python 3.8.6
from tkinter import *
import random
class test:
def __init__(self):
self.words = ["troop","relieve","exact","appeal","shortage","familiar","comfortable","sniff","mold","clay","rack","square","color","book","velvet","address","elaborate","grip","neutral","pupil"]
def scrollable_area2(self, holder):
base_frame = Frame(holder, padx=5, pady=5)
base_frame.pack(fill=BOTH, expand=1)
base_frame.rowconfigure(0, weight=0)
base_frame.columnconfigure(0, weight=1)
can = Canvas(base_frame, bg="white")
can.pack(side=LEFT, expand=1, fill=BOTH)
scrollArea = Frame(base_frame, bg="white", )
scrollArea.pack(side=LEFT, expand=1, fill=BOTH)
can.create_window(0, 0, window=scrollArea, anchor='nw')
Scroll = Scrollbar(base_frame, orient=VERTICAL)
Scroll.config(command=can.yview)
Scroll.pack(side=RIGHT, fill=Y)
can.config(yscrollcommand=Scroll.set)
scrollArea.bind("<Configure>", lambda e=Event(), c=can: self.update_scrollregion(e, c))
return scrollArea, can
def update_scrollregion(self, event, can):
if can.winfo_exists():
can.configure(scrollregion=can.bbox("all"))
def generate(self, count): #generates the rows
for i in range(int(count.get())):
row = Frame(self.holder)
row.pack(side=TOP)
for i in range(9):
a = Label(row, text=self.words[random.randint(0, len(self.words)-1)])
a.pack(side=LEFT)
b = Button(row, text=self.words[random.randint(0, len(self.words)-1)])
b.pack(side=LEFT)
def main(self):
opts = Frame(self.root)
opts.pack(side=TOP)
v= StringVar()
e = Entry(opts, textvariable=v)
e.pack(side=LEFT)
b=Button(opts, text="Run", command=lambda e=Event(), v=v:self.generate(v))
b.pack(side=LEFT)
main_frame=Frame(self.root)
main_frame.pack(side=TOP, fill=BOTH, expand=1)
self.holder, can = self.scrollable_area2(main_frame)
def run(self):
self.root = Tk()
self.main()
self.root.mainloop()
if __name__ == "__main__":
app = test()
app.run()
I have left a box where you can type the number of rows. I have tried from 30 rows to over 300 rows and although the initial render time changes the scroll issue is always the same.
NOTE: sorry about the weird way I am creating a scroll region, its from a more complex piece of code which I have modified to fit here if that ends up being a factor.
Since you are just creating a vertical stack of frames, it will likely be more efficient to use a text widget as the container rather than a canvas and embedded frame.
Here's a simple example that creates 1000 rows similar to how you're doing it with the canvas. On my OSX machine it performs much better than the canvas.
def scrollable_area2(self, parent):
base_frame = Frame(parent, padx=5, pady=5)
base_frame.pack(fill="both", expand=True)
holder = Text(base_frame)
vsb = Scrollbar(base_frame, orient="vertical", command=holder.yview)
holder.configure(yscrollcommand=vsb.set)
holder.pack(side="left", fill="both", expand=True)
vsb.pack(side="right", fill="y")
return holder
...
def generate(self, count): #generates the rows
for i in range(int(count.get())):
row = Frame(self.holder)
self.holder.window_create("end", window=row)
self.holder.insert("end", "\n")
...
def main(self):
...
self.holder = self.scrollable_area2(main_frame)
The above example keeps the inner frames, but you don't really need it. You can insert the text directly in the text widget, making the code even more efficient.
In a comment you said you aren't actually creating a stack of frames but rather a table of values. You can create a table in the text widget by using tabstops to create columns. By inserting text directly in the widget you're creating far fewer widgets which will definitely improve performance.
Here's an example using hard-coded the tabstops, but you could easily compute them based on the longest word in the list.
def scrollable_area2(self, parent):
base_frame = Frame(parent, padx=5, pady=5)
base_frame.pack(fill="both", expand=True)
self.holder = Text(base_frame, wrap="none", tabs=100)
vsb = Scrollbar(base_frame, orient="vertical", command=self.holder.yview)
self.holder.configure(yscrollcommand=vsb.set)
self.holder.pack(side="left", fill="both", expand=True)
vsb.pack(side="right", fill="y")
Your generate function then might look something like this:
def generate(self, count): #generates the rows
for i in range(int(count.get())):
for i in range(9):
text = "\t".join([random.choice(self.words) for x in range(9)])
self.holder.insert("end", text + "\t")
button = Button(self.holder, text=random.choice(self.words))
self.holder.window_create("end", window=button)
self.holder.insert("end", "\n")

TKInter - Confused about frames and scrolling

I am trying to code a tkinter application that has three frames - a top frame, where the user inputs some text, a dynamically constructed middle section where some pre-analysis is conducted on the text, and a bottom frame where, once the user has selected which option they want in the middle section, the output will be produced.
The problem is that, depending upon the input, there could be around 10-20 (and in the worst case 30) lines displayed and on a small monitor the output will disappear off the screen.
What I would like is for the top (input) and bottom (output) frames to be visible no matter how the screen is re-sized, and for the middle section to scroll (if required) and still allow the user to select their choice.
I am confused as to how to get the middle section to resize when the screen is resized, show a scrollbar if required, and still allow all of the content to be accessed.
I have created a cut-down version here (for simplicity, I have removed the processing methods and have instead created some fake output in a loop that resembles what the actual middle section would look like).
Please ignore the hideous colour-scheme - I was just trying to understand which frame went where (I will remove the colours as soon as I can!)
Thank you for any suggestions...
import tkinter as tk
from tkinter import scrolledtext
class MyApp(tk.Tk):
def __init__(self, title="Sample App", *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title(title)
self.configure(background="Gray")
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
# Create the overall frame:
master_frame = tk.Frame(self, bg="Light Blue", bd=3, relief=tk.RIDGE)
master_frame.grid(sticky=tk.NSEW)
master_frame.rowconfigure([0, 2], minsize=90) # Set min size for top and bottom
master_frame.rowconfigure(1, weight=1) # Row 1 should adjust to window size
master_frame.columnconfigure(0, weight=1) # Column 0 should adjust to window size
# Create the frame to hold the input field and action button:
input_frame = tk.LabelFrame(master_frame, text="Input Section", bg="Green", bd=2, relief=tk.GROOVE)
input_frame.grid(row=0, column=0, padx = 5, pady = 5, sticky=tk.NSEW)
input_frame.columnconfigure(0, weight=1)
input_frame.rowconfigure(0, weight=1)
# Create a frame for the middle (processing) section.
middle_frame = tk.LabelFrame(master_frame, text = "Processing Section")
middle_frame.grid(row=1, column=0, padx=5, pady=5, sticky=tk.NSEW)
# Create the frame to hold the output:
output_frame = tk.LabelFrame(master_frame, text="Output Section", bg="Blue", bd=2, relief=tk.GROOVE)
output_frame.grid(row=2, column=0, columnspan=3, padx=5, pady=5, sticky=tk.NSEW)
output_frame.columnconfigure(0, weight=1)
output_frame.rowconfigure(0, weight=1)
# Add a canvas in the middle frame.
self.canvas = tk.Canvas(middle_frame, bg="Yellow")
self.canvas.grid(row=0, column=0)
# Create a vertical scrollbar linked to the canvas.
vsbar = tk.Scrollbar(middle_frame, orient=tk.VERTICAL, command=self.canvas.yview)
vsbar.grid(row=0, column=1, sticky=tk.NS)
self.canvas.configure(yscrollcommand=vsbar.set)
# Content for the input frame, (one label, one input box and one button).
tk.Label(input_frame,
text="Please type, or paste, the text to be analysed into this box:").grid(row=0, columnspan = 3, sticky=tk.NSEW)
self.input_box = scrolledtext.ScrolledText(input_frame, height=5, wrap=tk.WORD)
self.input_box.columnconfigure(0, weight=1)
self.input_box.grid(row=1, column=0, columnspan = 3, sticky=tk.NSEW)
tk.Button(input_frame,
text="Do it!",
command=self.draw_choices).grid(row=2, column=2, sticky=tk.E)
# Content for the output frame, (one text box only).
self.output_box = scrolledtext.ScrolledText(output_frame, width=40, height=5, wrap=tk.WORD)
self.output_box.grid(row=0, column=0, columnspan=3, sticky=tk.NSEW)
def draw_choices(self):
""" This method will dynamically create the content for the middle frame"""
self.option = tk.IntVar() # Variable used to hold user's choice
self.get_input_text()
for i in range(30):
tk.Radiobutton(self.canvas,
text=f"Option {i + 1}: ", variable=self.option,
value=i,
command=self.do_analysis
).grid(row=i, column=0, sticky=tk.W)
tk.Label(self.canvas,
text=f"If you pick Option {i + 1}, the output will look like this: {self.shortText}.",
anchor=tk.W
).grid(row=i, column=1, sticky=tk.W)
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def get_input_text(self):
""" Will get the text from the input box and also create a shortened version to display on one line"""
screenWidth = 78
self.input_text = self.input_box.get(0.0, tk.END)
if len(self.input_text) > screenWidth:
self.shortText = self.input_text[:screenWidth]
else:
self.shortText = self.input_text[:]
self.shortText = self.shortText.replace('\n', ' ') # strip out carriage returns just in case
def do_analysis(self):
"""This will ultimately process and display the results"""
option = self.option.get() # Get option from radio button press
output_txt = f"You picked option {option + 1} and here is the output: \n{self.input_text}"
self.output_box.delete(0.0, tk.END)
self.output_box.insert(0.0, output_txt)
if __name__ == "__main__":
app = MyApp("My Simple Text Analysis Program")
app.mainloop()
I understand that you can't mix grid and pack geometries in the same container, and that a scrollbar must be attached to a canvas, and objects to be placed on that canvas must therefore be in yet another container so, attempting to follow Bryan's example, I created a minimal version of what I want - window with three sections - top, middle and bottom. The Top and bottom sections will contain a simple text field, the middle section will contain dynamic content and must be able to scroll as required.
Imports:
ScrollbarFrame
Extends class tk.Frame to support a scrollable Frame]
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("A simple GUI")
# Top frame
self.top_frame = tk.Frame(self, bg="LIGHT GREEN")
self.top_frame.pack(fill=tk.X)
tk.Label(self.top_frame, bg=self.top_frame.cget('bg'),
text="This is a label on the top frame")\
.grid(row=0, columnspan=3, sticky=tk.NSEW)
# Middle Frame
# Import from https://stackoverflow.com/a/62446457/7414759
# and don't change anything
sbf = ScrollbarFrame(self, bg="LIGHT BLUE")
sbf.pack(fill=tk.X, expand=True)
# self.middle_frame = tk.Frame(self, bg="LIGHT BLUE")
self.middle_frame = sbf.scrolled_frame
# Force scrolling by adding multiple Label
for _ in range(25):
tk.Label(self.middle_frame, bg=self.middle_frame.cget('bg'),
text="This is a label on the dynamic (middle) section")\
.grid()
# Bottom Frame
self.bottom_frame = tk.Frame(self, bg="WHITE")
self.bottom_frame.pack(fill=tk.X)
tk.Label(self.bottom_frame, bg=self.bottom_frame.cget('bg'),
text="This is a label on the bottom section")\
.grid(row=0, columnspan=3, sticky=tk.NSEW)
if __name__ == '__main__':
App().mainloop()

Tkinter - Expanding frame after (interactively) adding elements to it

I have the following code:
from tkinter import *
DEF_CHANNELS = {'iris': (255, 0, 0), 'sclera': (0, 255, 0), 'pupil': (0, 0, 255)}
class GUI(Tk):
def __init__(self, init_source, init_target, *args, **kw):
super().__init__(*args, **kw)
self.frame = Frame(self, height=400, width=500)
self.frame.pack(fill=BOTH, expand=YES)
self.channel_frame = Frame(self.frame, height=200, width=500, pady=16)
self.channel_frame.grid(column=0, row=0, columnspan=2)
self.channel_label = Label(self.channel_frame, text="Channel")
self.channel_label.grid(column=0, row=0)
self.colour_label = Label(self.channel_frame, text="Colour")
self.colour_label.grid(column=1, row=0)
self.channel_frames = []
for channel, colour in DEF_CHANNELS.items():
self.add_channel_frame(channel, colour)
self.channel_button = Button(self.channel_frame, text="+", command=self.add_channel_frame)
self.channel_button.grid(column=0, row=len(self.channel_frames) + 1)
def add_channel_frame(self, def_channel="", def_colour=""):
pair_frame = ChannelColourFrame(self.channel_frame, def_channel=def_channel, def_colour=def_colour, height=100, width=500, pady=2)
pair_frame.grid(column=0, row=len(self.channel_frames) + 1, columnspan=2)
self.channel_frames.append(pair_frame)
class ChannelColourFrame(Frame):
def __init__(self, *args, def_channel="", def_colour="", **kw):
super().__init__(*args, **kw)
self.channel_txt = Entry(self, width=30)
self.channel_txt.insert(END, def_channel)
self.channel_txt.grid(column=0, row=0)
self.colour_txt = Entry(self, width=30)
self.colour_txt.insert(END, def_colour)
self.colour_txt.grid(column=1, row=0)
self.color_picker_button = Button(self, text="\u2712")
self.color_picker_button.grid(column=2, row=0)
self.remove_button = Button(self, text="-", command=self.remove)
self.remove_button.grid(column=3, row=0)
def remove(self):
self.master.master.master.channel_frames.remove(self)
self.destroy()
gui = GUI('', '')
gui.mainloop()
The idea is to have a Frame that starts with 3 default text Entry pairs, which a user can arbitrarily remove/add. For the most part it works fine, but with one big problem. The Frame (self.channel_frame) never expands past its initial height, which causes problems when more than the initial 3 Entry pairs appear on it.
How do I make the entire Frame fit to the Entry pairs every time one is removed/added?
As an additional question, \u2712 appears as a box on my button, but it's supposed to be the black nib symbol (✒). Why isn't the symbol showing up despite being part of unicode?
You aren't creating any new rows, so it's not going to grow. At the start, you create three channel frames, and they are put in rows 0, 1, and 2. You then add a "+" button in row 4.
When you click the "+" button, it adds a new row at len(self.channel_frames) + 1. Since len(self.channel_frames) is 3, it adds the new frame at row 4, which is on top of the "+" button. Thus, you aren't adding a new row.
If you move the "+" button out of the frame, or move it down each time you add a new row, your code works fine.
For example:
def add_channel_frame(self, def_channel="", def_colour=""):
pair_frame = ChannelColourFrame(self.channel_frame, def_channel=def_channel, def_colour=def_colour, height=100, width=500, pady=2)
pair_frame.grid(column=0, row=len(self.channel_frames) + 1, columnspan=2)
self.channel_frames.append(pair_frame)
self.channel_button.grid(column=0, row=len(self.channel_frames)+1)
As an additional question, \u2712 appears as a box on my button, but it's supposed to be the black nib symbol (✒). Why isn't the symbol showing up despite being part of unicode?
Probably because the font you're using doesn't have that symbol. Try using a different font.

Tkinter capturing location of two different buttons in Button1 click and release

I have a grid of buttons in an 8x12 grid. Eventually, I want to be able to color a section (like a top left 3x3 grid) a specific color. For now, I have this question. Is it possible to get one button widget using button.bind("<Button-1>", myfunc2) and then get a second button widget using button.bind("<ButtonRelease-1>", myfunc2)? An outline of the code I have right now is below
class MyApp:
def __init__(self, main):
self.button_frame = tk.Frame(main)
tk.Grid.rowconfigure(root, 0, weight=1)
tk.Grid.columnconfigure(root, 0, weight=1)
self.button_frame.grid(row=0, column=0, sticky='nsew')
self.grid = tk.Frame(self.button_frame)
self.grid.grid(sticky='nsew', column=0, row=7, columnspan=2)
tk.Grid.rowconfigure(self.button_frame, 7, weight=1)
tk.Grid.columnconfigure(self.button_frame, 0, weight=1)
self.button_list = {}
self.createbuttongrid()
def createbuttongrid(self):
label = 1
for row in range(8):
for column in range(12):
button = tk.Button(self.button_frame, text='Well %s' % label)
button.bind("<Button-1>", self.buttonclick) # this line is in question
button.bind("<ButtonRelease-1>", self.buttonrelease) # along with this line
button.grid(row=row, column=column, sticky='nsew')
self.button_list[button] = (row, column)
label += 1
def buttonclick(self, event):
first_button = event.widget
print(self.button_list[first_button])
def buttonrelease(self, event):
second_button = event.widget
print(self.button_list[second_button])
if __name__ == "__main__":
import tkinter as tk
root = tk.Tk()
MyApp(main=root)
root.mainloop()
(The resizing (with the above example) doesn't work perfectly, but that's not important for now.)
Currently, when I run this and click on the top left button, I get (0, 0), and when I release I also get (0, 0). I think this is because the same widget is being passed into def buttonclick and def buttonrelease, but I'm not 100% sure
The <ButtonRelease> event will return the same widget that caught the <ButtonPress> event. That is due to the fact that clicking on a button causes the button to do a grab, which means all events are sent to the button rather than to any other button.
You can use the universal widget method winfo_containing to determine the widget at a given x/y coordinate. You must give it an x and y coordinate relative to the root window, which is conveniently supplied by the event object passed to an event handler.
def buttonrelease(event):
second_button = event.widget.winfo_containing(event.x_root, event.y_root)
...

Tkinter not able to fill the text box to the frame using grid. Used styling to add shadow and focus

Description
I am creating a canvas with scrollbar and adding frames with a text box in the frame and to fill the entire frame with no border. This will make it look as if the frame is the textbox. I have added shadow and styling to the frame (as coded by Bryan). This is added dynamically in for loop.
When I am trying to expand the text box to the frame, it is not expanding to fill the entire frame. There are extra spaces left.
Question
How do I fill up the entire frame with the textbox using a grid?
Code
import tkinter as tk
from tkinter import ttk
focusBorderImageData = '''
R0lGODlhQABAAPcAAHx+fMTCxKSipOTi5JSSlNTS1LSytPTy9IyKjMzKzKyq
rOzq7JyanNza3Ly6vPz6/ISChMTGxKSmpOTm5JSWlNTW1LS2tPT29IyOjMzO
zKyurOzu7JyenNze3Ly+vPz+/OkAKOUA5IEAEnwAAACuQACUAAFBAAB+AFYd
QAC0AABBAAB+AIjMAuEEABINAAAAAHMgAQAAAAAAAAAAAKjSxOIEJBIIpQAA
sRgBMO4AAJAAAHwCAHAAAAUAAJEAAHwAAP+eEP8CZ/8Aif8AAG0BDAUAAJEA
AHwAAIXYA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0FZIhM8sKGCQYCYA4cwcCEDSYPLOgg4Oro
uhMEdOB84cCAChReB2ZQYcGGkxsGFGCgGzCFCh1QH5jQIW3xugwSzD4QvIIH
4s/PUgiQYcCG4BkC5P/ObpaBhwreq18nb3Z79+8Dwo9nL9I8evjWsdOX6D59
fPH71Xeef/kFyB93/sln4EP2Ebjegg31B5+CEDLUIH4PVqiQhOABqKFCF6qn
34cHcfjffCQaFOJtGaZYkIkUuljQigXK+CKCE3po40A0trgjjDru+EGPI/6I
Y4co7kikkAMBmaSNSzL5gZNSDjkghkXaaGIBHjwpY4gThJeljFt2WSWYMQpZ
5pguUnClehS4tuMEDARQgH8FBMBBBExGwIGdAxywXAUBKHCZkAIoEEAFp33W
QGl47ZgBAwZEwKigE1SQgAUCUDCXiwtQIIAFCTQwgaCrZeCABAzIleIGHDD/
oIAHGUznmXABGMABT4xpmBYBHGgAKGq1ZbppThgAG8EEAW61KwYMSOBAApdy
pNp/BkhAAQLcEqCTt+ACJW645I5rLrgEeOsTBtwiQIEElRZg61sTNBBethSw
CwEA/Pbr778ABywwABBAgAAG7xpAq6mGUUTdAPZ6YIACsRKAAbvtZqzxxhxn
jDG3ybbKFHf36ZVYpuE5oIGhHMTqcqswvyxzzDS/HDMHEiiggQMLDxCZXh8k
BnEBCQTggAUGGKCB0ktr0PTTTEfttNRQT22ABR4EkEABDXgnGUEn31ZABglE
EEAAWaeN9tpqt832221HEEECW6M3wc+Hga3SBgtMODBABw00UEEBgxdO+OGG
J4744oZzXUEDHQxwN7F5G7QRdXxPoPkAnHfu+eeghw665n1vIKhJBQUEADs=
'''
root = tk.Tk()
style = ttk.Style()
borderImage = tk.PhotoImage("borderImage", data=borderImageData)
focusBorderImage = tk.PhotoImage("focusBorderImage", data=focusBorderImageData)
style.element_create("RoundedFrame",
"image", borderImage,
("focus", focusBorderImage),
border=16, sticky="nsew")
style.layout("RoundedFrame",
[("RoundedFrame", {"sticky": "nsew"})])
root.configure(background="white")
canvas = tk.Canvas(root)
scroll = tk.Scrollbar(root, orient='horizontal', command=canvas.xview)
canvas.configure(xscrollcommand=scroll.set)
frame = tk.Frame(canvas) # frame does not get pack() as it needs to be embedded into canvas throught canvas.
scroll.pack(side='bottom', fill='x')
canvas.pack(fill='both', expand='yes')
canvas.create_window((0,0), window=frame, anchor='nw')
frame.bind('<Configure>', lambda x: canvas.configure(scrollregion=canvas.bbox('all'))) # lambda function
for i in range(5):
frame1 = ttk.Frame(frame, style="RoundedFrame", padding=10)
journal1 = tk.Text(frame1, borderwidth=2, highlightthickness=0, width = 40, height = 38)
# journal1.configure(borderwidth="3")
journal1.configure(relief="groove")
journal1.configure(background="white")
journal1.grid(row=0, column=0, padx=(100, 10), sticky = 'nswe') # grid instead
journal1.bind("<FocusIn>", lambda event: frame.state(["focus"]))
journal1.bind("<FocusOut>", lambda event: frame.state(["!focus"]))
frame1.grid_columnconfigure(0, weight=1)
frame1.grid_rowconfigure(0, weight=1)
frame1.grid(row=0,column=i, sticky = 'nswe')
root.mainloop()
Output
I had troubles with the focus of the frame, it complained frame has no attribute 'state'. It works in Bryans original answer. I fixed it with closures.
def frameFocusCreator(frame, focusState):
def changeState(event):
frame.state([focusState])
return changeState
for i in range(5):
frame1 = ttk.Frame(frame, style="RoundedFrame", padding=10)
journal1 = tk.Text(frame1, borderwidth=0, highlightthickness=0, width = 40, height = 38)
journal1.configure(relief="groove")
journal1.configure(background="white")
journal1.pack(fill='both', expand=True)
journal1.bind("<FocusIn>", frameFocusCreator(frame1, "focus"))
journal1.bind("<FocusOut>", frameFocusCreator(frame1, "!focus"))
frame1.grid(row=0,column=i, sticky = 'nswe')

Resources