I recently made 2 functions, add_scrollbar and update_scroll_region, which adds a scrollbar to a given frame and updates the scroll region when widgets in that frame change.
The frame in which I am adding a scrollbar is a notebook tab. The functions work as intended, but when I switch off a tab with the scrollbar (and only the ones with the scrollbar) and come back to it, all the widgets are gone. If I move my mouse off of the tab label, all the widgets re-appear. I am not exactly sure what it is about these 2 functions that could be causing this kind of behavior. I have provided a simplified example below. In this example, TAB1 has the scrollbar, and TAB2 does not. You will notice that switching from TAB2 to TAB1 hides the button in TAB1 until the mouse is moved.
from tkinter import *
from tkinter import ttk
root = Tk()
root.geometry("1200x1200")
def add_scrollbar(outer_frame):
canvas = Canvas(outer_frame)
canvas.pack(side=LEFT, fill=BOTH, expand=1)
information_frame = Frame(canvas)
canvas.create_window((0, 0), window=information_frame)
scrollbar = ttk.Scrollbar(outer_frame, orient=VERTICAL, command=canvas.yview)
scrollbar.pack(side=RIGHT, fill=Y)
canvas.configure(yscrollcommand=scrollbar.set)
return information_frame, canvas
def update_scroll_region(canvas):
global root
root.update()
bbox = canvas.bbox("all")
x, y, width, height = bbox
if height < canvas.winfo_height():
bbox = x, y, width, canvas.winfo_height()
canvas.configure(scrollregion=bbox)
return
def create_example():
global root
notebook = ttk.Notebook(root, height=1200, width=1500)
notebook.pack(pady=10)
my_outer_frame_1 = Frame(root)
my_outer_frame_1.pack(fill=BOTH, expand=1)
notebook.add(my_outer_frame_1, text="TAB1")
inner_frame_1, my_canvas_1 = add_scrollbar(my_outer_frame_1)
my_outer_frame_2 = Frame(root)
my_outer_frame_2.pack(fill=BOTH, expand=1)
notebook.add(my_outer_frame_2, text="TAB2")
Label(my_outer_frame_2, text="This always shows").pack()
# ^^^ Sets up a notebook with 2 tabs
changing_frame = Frame(inner_frame_1, borderwidth=4) # this is the frame that will be changing its contents
changing_frame.pack(side=LEFT, anchor="n")
display_frame(changing_frame, my_outer_frame_1, my_canvas_1)
# this method re-displays the changing frame depending on the specified size ('big' or 'small')
root.mainloop()
return
def display_frame(frame, outer_frame, canvas, size='small'):
for widget in frame.winfo_children():
widget.destroy()
if size == 'small':
Button(frame, text="This button is gone until the mouse is moved",
command=lambda this_frame=frame: display_frame(this_frame, outer_frame, canvas, size='big')).grid(row=0,
column=0)
elif size == 'big':
Button(frame, height=5, width=5, text="Hide",
command=lambda this_frame=frame: display_frame(this_frame, outer_frame, canvas, size='small')).grid(
row=0, column=0)
for n in range(1, 100):
Label(frame, text="Other Stuff!").grid(row=n, column=0)
update_scroll_region(canvas)
return
if __name__ == '__main__':
create_example()
I am creating a game similar to bitlife in Tkinter. Although I have run into a problem. If you recall from bitlife, or any texting platform, you create text, then all the previously created text goes up. This existing text will then go into a scrollable frame (which I have already achieved). I am not asking for the straight up code, just any methods or ideas on how to make the previously created text go up. Thanks!
Not complete but I'm out of time.
Hacked together to show you how to add items to a canvas that very loosely looks like a text message application. Not pretty at all but I only had 10 mins
import tkinter as tk
class Message(tk.Frame):
def __init__(self,parent,name,text):
super().__init__(parent,width=250)
self.lblName = tk.Label(self, text=name, font=('Arial','10'))
self.lblName.grid(row=0,column=0)
self.lblText = tk.Message(self, text=text, font=('Arial','14'))
self.lblText.grid(row=1,column=1)
class MessageFrame(tk.Frame):
def __init__(self,parent):
super().__init__(parent)
# Add a canvas in that frame
self.canvas = tk.Canvas(self, bg="yellow")
self.canvas.grid(row=0, column=0, sticky="news")
# Link a scrollbar to the canvas
self.vsb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.vsb.grid(row=0, column=1, sticky='ns')
self.canvas.configure(yscrollcommand=self.vsb.set)
# Create a frame to contain the buttons
self.frame_buttons = tk.Frame(self.canvas, bg="blue")
self.canvas.create_window((0, 0), window=self.frame_buttons, anchor='nw')
self.messages = []
self.msgItems = []
def add_message(self, sender, text):
self.messages.append({'name':sender,'text':text})
self.refresh_msg_list()
def refresh_msg_list(self):
if self.msgItems:
for item in self.msgItems:
item.destroy()
self.msgItems = []
for idx,msg in enumerate(self.messages):
newItem = Message(self.frame_buttons, msg['name'], msg['text'])
#newItem = tk.Button(self.frame_buttons, text=task['task'])
newItem.grid(row=idx,column=0,sticky='news',pady=10)
self.msgItems.append(newItem)
# Update buttons frames idle tasks to let tkinter calculate buttons sizes
self.frame_buttons.update_idletasks()
# Resize the canvas frame to fit 5 messages
first5rows_height = max([task.winfo_height() for task in self.msgItems]) * 5
item_width = max([task.winfo_width() for task in self.msgItems])
##frame_canvas.config(width=first5columns_width + vsb.winfo_width(),
## height=first5rows_height)
self.config(height=first5rows_height,width=item_width+self.vsb.winfo_width())
# Set the canvas scrolling region
self.canvas.config(scrollregion=self.canvas.bbox("all"))
def add_new_item():
pass
def add_first_item():
msg.add_message('SenderName','How are you?')
msg.add_message('SenderName','How are you?')
msg.add_message('SenderName','How are you?')
msg.add_message('SenderName','How are you?')
msg.add_message('SenderName','How are you?')
root = tk.Tk()
root.grid_rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
frame_main = tk.Frame(root, bg="gray")
frame_main.grid(sticky='news')
# Create a frame for the canvas with non-zero row&column weights
msg = MessageFrame(frame_main)
msg.grid(row=2, column=0, pady=(5, 0), sticky='nw')
msg.grid_rowconfigure(0, weight=1)
msg.grid_columnconfigure(0, weight=1)
# Set grid_propagate to False to allow 5-by-5 buttons resizing later
msg.grid_propagate(False)
root.after_idle(add_first_item)
root.after(2000,add_new_item)
root.mainloop()
I am creating a simple application using tkinter.ttk. I am creating one Image Viewer App but while creating the app I am getting some problem. Here is my code:
from tkinter import *
from tkinter.ttk import *
from PIL import Image, ImageTk
root = Tk()
root.title("Simple Image Viewer")
style = Style()
root.columnconfigure(0, weight=True)
root.rowconfigure(0, weight=True)
img1 = ImageTk.PhotoImage(Image.open("images/img_1.jpg"))
img2 = ImageTk.PhotoImage(Image.open("images/img_2.jpg"))
img3 = ImageTk.PhotoImage(Image.open("images/img_3.jpg"))
images = [img1, img2, img3]
img_idx = 0
def previous_image():
global lbl_img
global images
global img_idx
img_idx = img_idx - 1
if img_idx < 0:
img_idx = len(images) - 1
try:
lbl_img.configure(image=images[img_idx])
except IndexError:
img_idx = -1
lbl_img.configure(image=images[img_idx])
finally:
status.configure(text=f"{img_idx + 1} of {len(images)} images.")
btn_back = Button(text="<", command=previous_image)
def forward_image():
global lbl_img
global images
global img_idx
img_idx = img_idx + 1
try:
lbl_img.configure(image=images[img_idx])
except IndexError:
img_idx = 0
lbl_img.configure(image=images[img_idx])
finally:
status.configure(text=f"{img_idx + 1} of {len(images)} images.")
btn_forward = Button(text=">", command=forward_image)
lbl_img = Label(image=images[img_idx])
status = Label(root, text=f"{img_idx + 1} of {len(images)} images.", borderwidth=1,
relief=SUNKEN, anchor="e")
status.grid(row=2, column=0, columnspan=3, stick=W+E)
btn_exit = Button(text="Exit", command=root.quit)
btn_back.grid(row=0, column=0, stick=W)
lbl_img.grid(row=0, column=1)
btn_forward.grid(row=0, column=2, stick=E)
btn_exit.grid(row=1, column=1)
root.mainloop()
When I run this then it comes like this:
In small window
And when I maximize it: In maximize
It comes like this. In above picture you can see that the image is not coming properly in center. My pictures must be in exact center in both in small and big window. Please can any one help me to do that by seeing my program.
Thanks in advance
You can achieve this with grid you need to make sure that left and right get space, also up and down, but the middle gets no space. As an exampel:
import tkinter as tk
root = tk.Tk()
up = tk.Frame(root)
up.grid(column=0, row=0,columnspan=3,sticky='n')
s1 = tk.Label(up, text='spacer')
s1.pack()
left = tk.Frame(root)
b1 = tk.Button(left, text='B1')
left.grid(column=0,row=1,sticky='w')
b1.pack()
middle = tk.Frame(root)
middle.grid(column=1, row=1)
s2 = tk.Label(middle, text='spacer')
s2.pack()
down = tk.Frame(root)
qb = tk.Button(down, text='Exit', command= root.destroy)
down.grid(column=0, row=2,columnspan=3,sticky='s')
qb.pack()
right = tk.Frame(root)
right.grid(column=2,row=1,sticky='e')
b2 = tk.Button(right, text='B2')
b2.pack()
root.columnconfigure(0,weight=1) #left get space
root.columnconfigure(2,weight=1) #right get space
root.rowconfigure(0, weight=1) #up get space
root.rowconfigure(2, weight=1) #down get space
root.mainloop()
Ourput:
For detail information what weight does.
I think there are 2 solutions you can do for this.
When you are displaying your image onto the program you can do ....place(x=x_coord, y=y_coord, anchor=center) to make sure that the image is set and always is in the center of the program.
One tip is to set the resolution of the program at the very start and instead of using grids you can use coordinates and anchors which will place your buttons and images nicely (I think), I haven't tried it with images.
Another solution which will probably fix your problem is determining if you want your program to be full screen. If you want your program to stay in a nice small window like on your first reference you can prevent the user from resizing the window. When you are maximizing the window you have not made the image to resize as the window gets bigger so I'm sure this is fine to do. At the start of your program after you define root... root.resizable(0, 0). This will prevent the user from resizing the window.
I implemented what you said but the buttons for me it is not perfect. I want to put the buttons on top of the label, I don't want them on the side.it is posible?
import tkinter as tk
root = tk.Tk()
image_list = getfiles()
up = tk.Frame(root)
up.grid(column=0, row=0,columnspan=3,sticky='n')
s1 = tk.Label(up, text='spacer')
s1.pack()
left = tk.Frame(root)
b1 = tk.Button(left, text='B1')
left.grid(column=0,row=1,sticky='w')
b1.pack()
middle = tk.Frame(root)
middle.grid(column=1, row=1)
s2 = tk.Label(middle, text='spacer')
image = Image.open(image_list[current])
photo = ImageTk.PhotoImage(image)
s2['image'] = photo
s2.photo = photo
s2.pack()
down = tk.Frame(root)
qb = tk.Button(down, text='Exit', command= root.destroy)
down.grid(column=0, row=2,columnspan=3,sticky='s')
qb.pack()
right = tk.Frame(root)
right.grid(column=2,row=1,sticky='e')
b2 = tk.Button(right, text='B2')
b2.pack()
root.columnconfigure(0,weight=1) #left get space
root.columnconfigure(2,weight=1) #right get space
root.rowconfigure(0, weight=1) #up get space
root.rowconfigure(2, weight=1) #down get space
root.mainloop()
To put the button in the same place than a Image you need place()
label = Tkinter.Label(root, compound=Tkinter.TOP)
label.pack()
A=Tkinter.Button(root, text='Previous picture', command=lambda: move(-1))
A.place(relx=0, x=2, y=20,width=130,height=100)
B=Tkinter.Button(root, text='Next picture', command=lambda: move(+1))
B.place(relx=0, x=135, y=20,width=130,height=100)
C=Tkinter.Button(root, text='PRINT', command=root.quit)
C.place(relx=1, x=-130, y=20,width=130,height=100)
move(0)
root.update()
root.mainloop()
My objective is to add a vertical scroll bar to a frame which has several labels in it. The scroll bar should automatically enabled as soon as the labels inside the frame exceed the height of the frame. After searching through, I found this useful post. Based on that post I understand that in order to achieve what i want, (correct me if I am wrong, I am a beginner) I have to create a Frame first, then create a Canvas inside that frame and stick the scroll bar to that frame as well. After that, create another frame and put it inside the canvas as a window object. So, I finally come up with this:
from Tkinter import *
def data():
for i in range(50):
Label(frame,text=i).grid(row=i,column=0)
Label(frame,text="my text"+str(i)).grid(row=i,column=1)
Label(frame,text="..........").grid(row=i,column=2)
def myfunction(event):
canvas.configure(scrollregion=canvas.bbox("all"),width=200,height=200)
root=Tk()
sizex = 800
sizey = 600
posx = 100
posy = 100
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
myframe=Frame(root,relief=GROOVE,width=50,height=100,bd=1)
myframe.place(x=10,y=10)
canvas=Canvas(myframe)
frame=Frame(canvas)
myscrollbar=Scrollbar(myframe,orient="vertical",command=canvas.yview)
canvas.configure(yscrollcommand=myscrollbar.set)
myscrollbar.pack(side="right",fill="y")
canvas.pack(side="left")
canvas.create_window((0,0),window=frame,anchor='nw')
frame.bind("<Configure>",myfunction)
data()
root.mainloop()
Am I doing it right? Is there better/smarter way to achieve the output this code gave me?
Why must I use grid method? (I tried place method, but none of the labels appear on the canvas.)
What so special about using anchor='nw' when creating window on canvas?
Please keep your answer simple, as I am a beginner.
Here's example code adapted from the VerticalScrolledFrame page on the now defunct Tkinter Wiki that's been modified to run on Python 2.7 and 3+.
try: # Python 2
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
except ImportError: # Python 2
import Tkinter as tk
import ttk
from tkinter.constants import *
# Based on
# https://web.archive.org/web/20170514022131id_/http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame
class VerticalScrolledFrame(ttk.Frame):
"""A pure Tkinter scrollable frame that actually works!
* Use the 'interior' attribute to place widgets inside the scrollable frame.
* Construct and pack/place/grid normally.
* This frame only allows vertical scrolling.
"""
def __init__(self, parent, *args, **kw):
ttk.Frame.__init__(self, parent, *args, **kw)
# Create a canvas object and a vertical scrollbar for scrolling it.
vscrollbar = ttk.Scrollbar(self, orient=VERTICAL)
vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
canvas = tk.Canvas(self, bd=0, highlightthickness=0,
yscrollcommand=vscrollbar.set)
canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vscrollbar.config(command=canvas.yview)
# Reset the view
canvas.xview_moveto(0)
canvas.yview_moveto(0)
# Create a frame inside the canvas which will be scrolled with it.
self.interior = interior = ttk.Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior,
anchor=NW)
# Track changes to the canvas and frame width and sync them,
# also updating the scrollbar.
def _configure_interior(event):
# Update the scrollbars to match the size of the inner frame.
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
# Update the canvas's width to fit the inner frame.
canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
# Update the inner frame's width to fill the canvas.
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
canvas.bind('<Configure>', _configure_canvas)
if __name__ == "__main__":
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
root = tk.Tk.__init__(self, *args, **kwargs)
self.frame = VerticalScrolledFrame(root)
self.frame.pack()
self.label = ttk.Label(self, text="Shrink the window to activate the scrollbar.")
self.label.pack()
buttons = []
for i in range(10):
buttons.append(ttk.Button(self.frame.interior, text="Button " + str(i)))
buttons[-1].pack()
app = SampleApp()
app.mainloop()
It does not yet have the mouse wheel bound to the scrollbar but it is possible. Scrolling with the wheel can get a bit bumpy, though.
edit:
to 1)
IMHO scrolling frames is somewhat tricky in Tkinter and does not seem to be done a lot. It seems there is no elegant way to do it.
One problem with your code is that you have to set the canvas size manually - that's what the example code I posted solves.
to 2)
You are talking about the data function? Place works for me, too. (In general I prefer grid).
to 3)
Well, it positions the window on the canvas.
One thing I noticed is that your example handles mouse wheel scrolling by default while the one I posted does not. Will have to look at that some time.
"Am i doing it right?Is there better/smarter way to achieve the output this code gave me?"
Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of code to make it work -- depending on how you count lines.
"Why must i use grid method?(i tried place method, but none of the labels appear on the canvas?)"
You ask about why you must use grid. There is no requirement to use grid. Place, grid and pack can all be used. It's simply that some are more naturally suited to particular types of problems. In this case it looks like you're creating an actual grid -- rows and columns of labels -- so grid is the natural choice.
"What so special about using anchor='nw' when creating window on canvas?"
The anchor tells you what part of the window is positioned at the coordinates you give. By default, the center of the window will be placed at the coordinate. In the case of your code above, you want the upper left ("northwest") corner to be at the coordinate.
Please see my class that is a scrollable frame. It's vertical scrollbar is binded to <Mousewheel> event as well. So, all you have to do is to create a frame, fill it with widgets the way you like, and then make this frame a child of my ScrolledWindow.scrollwindow. Feel free to ask if something is unclear.
Used a lot from # Brayan Oakley answers to close to this questions
class ScrolledWindow(tk.Frame):
"""
1. Master widget gets scrollbars and a canvas. Scrollbars are connected
to canvas scrollregion.
2. self.scrollwindow is created and inserted into canvas
Usage Guideline:
Assign any widgets as children of <ScrolledWindow instance>.scrollwindow
to get them inserted into canvas
__init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs)
docstring:
Parent = master of scrolled window
canv_w - width of canvas
canv_h - height of canvas
"""
def __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs):
"""Parent = master of scrolled window
canv_w - width of canvas
canv_h - height of canvas
"""
super().__init__(parent, *args, **kwargs)
self.parent = parent
# creating a scrollbars
self.xscrlbr = ttk.Scrollbar(self.parent, orient = 'horizontal')
self.xscrlbr.grid(column = 0, row = 1, sticky = 'ew', columnspan = 2)
self.yscrlbr = ttk.Scrollbar(self.parent)
self.yscrlbr.grid(column = 1, row = 0, sticky = 'ns')
# creating a canvas
self.canv = tk.Canvas(self.parent)
self.canv.config(relief = 'flat',
width = 10,
heigh = 10, bd = 2)
# placing a canvas into frame
self.canv.grid(column = 0, row = 0, sticky = 'nsew')
# accociating scrollbar comands to canvas scroling
self.xscrlbr.config(command = self.canv.xview)
self.yscrlbr.config(command = self.canv.yview)
# creating a frame to inserto to canvas
self.scrollwindow = ttk.Frame(self.parent)
self.canv.create_window(0, 0, window = self.scrollwindow, anchor = 'nw')
self.canv.config(xscrollcommand = self.xscrlbr.set,
yscrollcommand = self.yscrlbr.set,
scrollregion = (0, 0, 100, 100))
self.yscrlbr.lift(self.scrollwindow)
self.xscrlbr.lift(self.scrollwindow)
self.scrollwindow.bind('<Configure>', self._configure_window)
self.scrollwindow.bind('<Enter>', self._bound_to_mousewheel)
self.scrollwindow.bind('<Leave>', self._unbound_to_mousewheel)
return
def _bound_to_mousewheel(self, event):
self.canv.bind_all("<MouseWheel>", self._on_mousewheel)
def _unbound_to_mousewheel(self, event):
self.canv.unbind_all("<MouseWheel>")
def _on_mousewheel(self, event):
self.canv.yview_scroll(int(-1*(event.delta/120)), "units")
def _configure_window(self, event):
# update the scrollbars to match the size of the inner frame
size = (self.scrollwindow.winfo_reqwidth(), self.scrollwindow.winfo_reqheight())
self.canv.config(scrollregion='0 0 %s %s' % size)
if self.scrollwindow.winfo_reqwidth() != self.canv.winfo_width():
# update the canvas's width to fit the inner frame
self.canv.config(width = self.scrollwindow.winfo_reqwidth())
if self.scrollwindow.winfo_reqheight() != self.canv.winfo_height():
# update the canvas's width to fit the inner frame
self.canv.config(height = self.scrollwindow.winfo_reqheight())
For anyone who stumbles across this (as it did when looking for my own gist) I maintain a gist for exactly this purpose at https://gist.github.com/mp035/9f2027c3ef9172264532fcd6262f3b01 It has scrollwheel support for various operating systems, is commented, and has a built-in demo in the file.
We can add scroll bar even without using Canvas. I have read it in many other post we can't add vertical scroll bar in frame directly etc etc. But after doing many experiment found out way to add vertical as well as horizontal scroll bar :). Please find below code which is used to create scroll bar in treeView and frame.
f = Tkinter.Frame(self.master,width=3)
f.grid(row=2, column=0, columnspan=8, rowspan=10, pady=30, padx=30)
f.config(width=5)
self.tree = ttk.Treeview(f, selectmode="extended")
scbHDirSel =tk.Scrollbar(f, orient=Tkinter.HORIZONTAL, command=self.tree.xview)
scbVDirSel =tk.Scrollbar(f, orient=Tkinter.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scbVDirSel.set, xscrollcommand=scbHDirSel.set)
self.tree["columns"] = (self.columnListOutput)
self.tree.column("#0", width=40)
self.tree.heading("#0", text='SrNo', anchor='w')
self.tree.grid(row=2, column=0, sticky=Tkinter.NSEW,in_=f, columnspan=10, rowspan=10)
scbVDirSel.grid(row=2, column=10, rowspan=10, sticky=Tkinter.NS, in_=f)
scbHDirSel.grid(row=14, column=0, rowspan=2, sticky=Tkinter.EW,in_=f)
f.rowconfigure(0, weight=1)
f.columnconfigure(0, weight=1)
It is nessesery to configure Scrollbar in case of using with Canvas
by sending to Canvas xscrollcommand attribute Scrollbar.set method and
to Scrollbar command attribute Canvas.yview (xview) method.
Canvas.yview method after scrollbar was moved recieve *args in next formatting:
tuple('move_to', '<some_absolute_float_value_of_top_of_scrollbar_region>')
In case of implementing scrollability to widget,
Recieving region and translating scrollbar_region (whith element viewable and whith not) features must be created.
Region is `tuple(float, float)' representing open to see part of all elements.
Not ideal bechavior showed in this solution (without using tk.Canvas)
import tkinter as tk
from tkinter import ttk
class ItemizeFrame(ttk.Frame, list):
def __init__(self,
*args,
scroll_upd_callback = lambda x: x,
visible_els: int = 10,
**kwargs):
list.__init__(self)
ttk.Frame.__init__(self, *args, **kwargs)
ttk.Style().configure('Small.TButton', background='red', width=2, height=2, padx=3, pady=3)
ttk.Style().configure('Sep.TFrame', padx=3, pady=3)
self.scroll_upd_callback = scroll_upd_callback
self.visible_els = visible_els
self.visible_st_idx = 0
self.pseudo_scroll_element_cursor_line = 0.5*1/visible_els
def append(self, item: ttk.Widget, **kw):
e = item(self, **kw)
super().append(e)
e.pack(fill='x')
self._update_visible_els()
def _update_visable_id_callback(self):
for id_, entry_ in enumerate(self):
entry_.set_id(id_)
def pop(self, index=None):
e = super().pop(index)
e.destroy()
self._update_visible_els()
def __getitem__(self, idx) -> ttk.Widget:
return list.__getitem__(self, idx)
# indicators computing and application
#property
def visible_end_idx(self):
return self.visible_st_idx + self.visible_els -1
#property
def visible_area_ratio(self) -> tuple[float, float]:
total = len(self)
st_val = 0.0
end_val = 1.0
if total > self.visible_els:
end_val = 1.0 - (total-self.visible_end_idx)/total
st_val = self.visible_st_idx / total
st_val = st_val + self.pseudo_scroll_element_cursor_line
end_val = end_val + self.pseudo_scroll_element_cursor_line
return (st_val, end_val)
def _update_scroll_widget(self):
self.scroll_upd_callback(*self.visible_area_ratio)
def set_yview(self, move_to_ratio):
base_pseudo_ratio = 0.5*1/self.visible_els
total = len(self)
max_ratio = (total - self.visible_els)/total+base_pseudo_ratio
if move_to_ratio < 0:
possible_st_el_pseudo_part = base_pseudo_ratio
possible_st_el_idx = 0
if max_ratio < move_to_ratio:
possible_st_el_idx = total - self.visible_els
possible_st_el_pseudo_part = base_pseudo_ratio
else :
el_idx_raw = move_to_ratio * total
el_idx_round = round(el_idx_raw)
el_idx_pseudo = (el_idx_raw - el_idx_round)*1/self.visible_els
possible_st_el_idx = el_idx_round
possible_st_el_pseudo_part = el_idx_pseudo
self.visible_st_idx = possible_st_el_idx
self.pseudo_scroll_element_cursor_line = possible_st_el_pseudo_part
self._update_visible_els()
def _update_visible_els(self):
for el in self:
el.pack_forget()
for num, el in enumerate(self):
if self.visible_st_idx <= num and num <= self.visible_end_idx:
el.pack()
self._update_scroll_widget()
class ScrollableFrame(ttk.Frame):
def __init__(self, *args, **kwargs):
kw = dict(width=400, height=300)
kw.update(kwargs)
super().__init__(*args, **kw)
self.scroll = ttk.Scrollbar(self, command=self.on_scroll)
self.scroll.pack(expand=True, fill='y', side='right')
self.view = ItemizeFrame(
self,
scroll_upd_callback=self.scroll.set,
**kwargs
)
self.view.pack(expand=True, fill='both')#, side='left')
def on_scroll(self, *args, **kwargs):
value_raw = float(args[1])
self.view.set_yview(value_raw)
Usecase
class App(tk.Tk):
def __init__(self):
super().__init__()
self.frame = ScrollableFrame(self)
self.frame.pack()
def test_fill(self):
for i in range(15):
self.frame.view.append(ttk.Entry)
class Test:
#staticmethod
def v2():
app = App()
app.test_fill()
app.mainloop()
Test.v2()
After I watching many answers, I got it:
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")
def onFrameConfigure(canvas):
'''Reset the scroll region to encompass the inner frame'''
canvas.configure(scrollregion=canvas.bbox("all"))
'''When window size change, canvas size will change,
use this line to change its item size (width).'''
canvas.itemconfigure(wrapFrame, width=canvas.winfo_width())
canvas = tk.Canvas(root, highlightthickness=0)
frame = tk.Frame(canvas, background="#FFFFFF")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)
vsb.pack(side="right", fill="y")
canvas.pack(fill="both", expand=1, anchor="nw") #canvas size is relative to window size.
wrapFrame = canvas.create_window((0,0), window=frame, anchor="nw")
# When the window size change, it will call this function
canvas.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))
L1 = tk.Label(frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")
for i in range(100):
input = tk.Entry(frame)
input.pack()
root.mainloop()
Specifies the size of the scrollable frame by changing canvas and scrollbar position and size.
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")
def onFrameConfigure(canvas):
'''Reset the scroll region to encompass the inner frame'''
canvas.configure(scrollregion=canvas.bbox("all"))
canvas.itemconfigure(wrapFrame, width=canvas.winfo_width())
canvas = tk.Canvas(root, highlightthickness=0)
frame = tk.Frame(canvas, background="#FFFFFF")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)
vsb.place(relx=0.9, y=0, relwidth=0.1, relheight=0.5)
canvas.place(x=0, y=0, relwidth=0.9, relheight=0.5)
wrapFrame = canvas.create_window((0,0), window=frame, anchor="nw")
canvas.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))
L1 = tk.Label(frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")
for i in range(100):
input = tk.Entry(frame)
input.pack()
root.mainloop()
Specifies the size of the scrollable frame by writing them to outerFrame.
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")
def onFrameConfigure(canvas):
'''Reset the scroll region to encompass the inner frame'''
canvas.configure(scrollregion=canvas.bbox("all"))
canvas.itemconfigure(wrapFrame, width=canvas.winfo_width())
outerFrame = tk.Frame(root)
canvas = tk.Canvas(outerFrame, highlightthickness=0)
frame = tk.Frame(canvas, background="#FFFFFF")
vsb = tk.Scrollbar(outerFrame, orient="vertical", command=canvas.yview)
canvas.config(yscrollcommand=vsb.set)
outerFrame.place(relx=0.25, rely=0.1, relwidth=0.5, relheight=0.5)
vsb.pack(side="right", fill="y")
canvas.pack(fill="both", expand=1, anchor="nw")
wrapFrame = canvas.create_window((0,0), window=frame, anchor="nw")
canvas.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))
L1 = tk.Label(frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")
for i in range(100):
input = tk.Entry(frame)
input.pack()
root.mainloop()
The items inner the frame can use pack or grid (only choose one), but place cannot be used alone. If you want to use place, you need to expand the layout(height) with pack or grid first.
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")
def onFrameConfigure(canvas):
'''Reset the scroll region to encompass the inner frame'''
canvas.configure(scrollregion=canvas.bbox("all"))
canvas.itemconfigure(wrapFrame, width=canvas.winfo_width())
canvas = tk.Canvas(root, highlightthickness=0)
frame = tk.Frame(canvas, background="#FFFFFF")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)
vsb.pack(side="right", fill="y")
canvas.pack(fill="both", expand=1, anchor="nw")
wrapFrame = canvas.create_window((0,0), window=frame, anchor="nw")
canvas.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))
L1 = tk.Label(frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")
for i in range(100):
input = tk.Entry(frame)
input.pack()
L1 = tk.Label(frame, text="我是Label")
L1.place(x=0, rely=0.5)
root.mainloop()
Use mouse wheel:
tkinter: binding mousewheel to scrollbar
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")
def onFrameConfigure(canvas):
canvas.configure(scrollregion=canvas.bbox("all"))
canvas.itemconfigure(wrapFrame, width=canvas.winfo_width())
def on_mouse_wheel(event, scale=3):
#only care event.delta is - or +, scroll down or up
if event.delta<0:
canvas.yview_scroll(scale, "units")
else:
canvas.yview_scroll(-scale, "units")
canvas = tk.Canvas(root, highlightthickness=0)
frame = tk.Frame(canvas, background="#FFFFFF")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)
vsb.pack(side="right", fill="y")
canvas.pack(fill="both", expand=1, anchor="nw")
wrapFrame = canvas.create_window((0,0), window=frame, anchor="nw")
canvas.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))
canvas.bind("<Enter>", lambda event: canvas.bind_all("<MouseWheel>", on_mouse_wheel)) # on mouse enter
canvas.bind("<Leave>", lambda event: canvas.unbind_all("<MouseWheel>")) # on mouse leave
L1 = tk.Label(frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")
for i in range(100):
input = tk.Entry(frame)
input.pack()
root.mainloop()
Export to class:
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")
class scrollFrame():
def __init__(self, **options):
outerFrame = tk.Frame(root)
canvas = tk.Canvas(outerFrame, highlightthickness=0)
vsb = tk.Scrollbar(outerFrame, orient="vertical", command=canvas.yview)
vsb.pack(side="right", fill="y")
canvas.pack(fill="both", expand=1, anchor="nw")
frame = tk.Frame(canvas, **options)
wrapFrameId = canvas.create_window((0,0), window=frame, anchor="nw")
canvas.config(yscrollcommand=vsb.set)
canvas.bind("<Configure>", lambda event: self.onFrameConfigure())
canvas.bind("<Enter>", lambda event: canvas.bind_all("<MouseWheel>", self.on_mouse_wheel)) # on mouse enter
canvas.bind("<Leave>", lambda event: canvas.unbind_all("<MouseWheel>")) # on mouse leave
self.outerFrame, self.canvas, self.vsb, self.frame, self.wrapFrameId = outerFrame, canvas, vsb, frame, wrapFrameId
def onFrameConfigure(self):
canvas = self.canvas
'''Reset the scroll region to encompass the inner frame'''
canvas.configure(scrollregion=canvas.bbox("all"))
canvas.itemconfigure(self.wrapFrameId, width=canvas.winfo_width())
def on_mouse_wheel(self, event, scale=3):
canvas = self.canvas
#only care event.delta is - or +, scroll down or up
if event.delta<0:
canvas.yview_scroll(scale, "units")
else:
canvas.yview_scroll(-scale, "units")
frame = scrollFrame(background="#FFFFFF")
frame.outerFrame.place(relx=0.15, rely=0.1, relwidth=0.7, relheight=0.8)
L1 = tk.Label(frame.frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")
for i in range(100):
input = tk.Entry(frame.frame)
input.pack()
root.mainloop()
According:
https://stackoverflow.com/a/3092341/19470749
https://stackoverflow.com/a/16198198/19470749
https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/create_window.html
Not 100% sure if this solution is on topic (since it explicitely asks for a scrollable FRAME), but the text widget is basically a scrollable Frame.
From documentation of the Text widget:
"Like canvas widgets, text widgets can contain images and any other Tk widgets (including frames containing many other widgets). In a sense, this allows the text widget to work as a geometry manager in its own right. "
Text widgets are very easy to use, and can be made scrollable. So instead of using a special Class like the Scrollable Frame, I think the Text widget is a great option.
Below my code, for a basic example of a scrollable text widget holding 100 buttons:
from tkinter import Tk, Button, Text,Scrollbar
class test:
def __init__(self):
self.win = Tk()
text = Text(self.win, width=40, height=10, wrap = "none")
ys = Scrollbar(self.win, orient = 'vertical', command = text.yview)
text['yscrollcommand'] = ys.set
text.grid(column = 0, row = 0, sticky = 'nwes')
ys.grid(column = 1, row = 0, sticky = 'ns')
for x in range(1,100):
b = Button(text, text='Push Me')
text.window_create("end", window=b)
text.insert("end",'\n')
self.win.mainloop()
test = test()
This is at least the method I am going to use for my scrollable frames. Not sure if there is a better solution then the newline insertion to make the widgets organised vertically. But it works.