adding x and y Scrollbar to a canvas - python

Creating a program that will place an image onto a canvas. I want to add an X-axis, and Y-axis scrollbar onto the canvas, but I am not sure how to.
I would normally use a Frame, but the program I'm working on is using tkinter.Toplevel instead of using a Frame.
#----- Imports ---------------------
import os
import os.path
import sys
import tkinter
tk = tkinter
from tkinter import font
#----- Set flag for JPEG support ---
noJPEG = False
try:
from PIL import Image
Pimg = Image
from PIL import ImageDraw
Pdraw = ImageDraw.Draw
from PIL import ImageTk
Pimgtk = ImageTk
except ImportError:
noJPEG = True
#
#------------------------------------
# Create an invisible global parent window to hold all children.
# Facilitates easy closing of all windows by a mouse click.
_root = tk.Tk()
_root.withdraw()
#
#------------------------------------
# A writeable window for holding an image.
#
class ImageView(tk.Canvas):
def __init__(self, image, title=''):
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW", self.close)
tk.Canvas.__init__(self, master,
width = 600, height = 500,
scrollregion=(0,0, image.getWidth(),
image.getHeight()))
# Define class fields
## Image properties
self.master.title(title)
self.pack()
master.resizable(0,0)
self.foreground = "black"
self.image = image
self.height = image.getHeight()
self.width = image.getWidth()
# for later
#self.customFont = font.Font(family="Helvetica", size=12)
## Actionable items
self.mouseX = None
self.mouseY = None
self.mouseFxn = None
self.bind("<Button-1>", self.onClick) #bind action to button1 click
self.tags = None
_root.update() #redraw global window

There's nothing special about using a Toplevel rather than a Frame. You attach a scrollbar the way you do it for any scrollable widget in any container.
I've never seen a widget create it's own parent. That's quite unusual, though it really doesn't change anything. Just add the scrollbars inside the toplevel.
You might want to switch to grid instead of pack since that makes it a bit easier to get the scrollbars to line up properly. You just need to remove the call to self.pack(), and add something like this to your code:
vsb = tk.Scrollbar(master, orient="vertical", command=self.yview)
hsb = tk.Scrollbar(master, orient="horizontal", command=self.xview)
self.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
self.grid(row=0, column=0, sticky="nsew")
vsb.grid(row=0, column=1, sticky="ns")
hsb.grid(row=1, column=0, sticky="ew")
master.grid_rowconfigure(0, weight=1)
master.grid_columnconfigure(0, weight=1)

Related

Python tkinter window resizes, but widgets never change or move

Python beginner. I placed a scrollbar widget in window and that works, but no matter what I do I can't get the scrollbox widget to change size. Could go with a larger scrollbox or for it to resize when the window resizes, but can't figure out how to force either to happen. Tried lots of different solutions, but feels like the grid and canvas are defaulting to a size and can't figure out how to change that. Help would be appreciated. Code is below:
import tkinter as tk
from tkinter import ttk
import os
import subprocess
class Scrollable(tk.Frame):
"""
Make a frame scrollable with scrollbar on the right.
After adding or removing widgets to the scrollable frame,
call the update() method to refresh the scrollable area.
"""
def __init__(self, frame, width=16):
scrollbar = tk.Scrollbar(frame, width=width)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y, expand=True)
self.canvas = tk.Canvas(frame, yscrollcommand=scrollbar.set)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.config(command=self.canvas.yview)
self.canvas.bind('<Configure>', self.__fill_canvas)
# base class initialization
tk.Frame.__init__(self, frame)
# assign this obj (the inner frame) to the windows item of the canvas
self.windows_item = self.canvas.create_window(0,0, window=self, anchor=tk.NW)
def __fill_canvas(self, event):
"Enlarge the windows item to the canvas width"
canvas_width = event.width
self.canvas.itemconfig(self.windows_item, width = canvas_width)
def update(self):
"Update the canvas and the scrollregion"
self.update_idletasks()
self.canvas.config(scrollregion=self.canvas.bbox(self.windows_item))
root = tk.Tk()
root.title("application")
root.geometry('750x800')
dbEnvs = ['a','b']
x = 1
header = ttk.Frame(root)
body = ttk.Frame(root)
footer = ttk.Frame(root)
header.pack(side = "top")
body.pack()
footer.pack(side = "top")
#setup Environment selection
envLabel = tk.Label(header, text="Environment:")
envLabel.grid(row=0,column=0,sticky='nw')
dbselection = tk.StringVar()
scrollable_body = Scrollable(body, width=20)
x = 1
for row in range(50):
checkboxVar = tk.IntVar()
checkbox = ttk.Checkbutton(scrollable_body, text=row, variable=checkboxVar)
checkbox.var = checkboxVar # SAVE VARIABLE
checkbox.grid(row=x, column=1, sticky='w')
x += 1
scrollable_body.update()
#setup buttons on the bottom
pullBtn = tk.Button(footer, text='Pull')
pullBtn.grid(row=x, column=2, sticky='ew')
buildBtn = tk.Button(footer, text='Build')
buildBtn.grid(row=x, column=3, sticky='ew')
compBtn = tk.Button(footer, text='Compare')
compBtn.grid(row=x, column=4, sticky='ew')
root.mainloop()
have tried anchoring, changing the window base size and multiple other things (8 or 19 different items, plus reading lots of posts), but they normally involve packing and since I used grids that normally and ends with more frustration and nothing changed.
If you want the whole scrollbox to expand to fill the body frame, you must instruct pack to do that using the expand and fill options:
body.pack(side="top", fill="both", expand=True)
Another problem is that you're setting expand to True for the scrollbar. That's probably not something you want to do since it means the skinny scrollbar will be allocated more space than is needed. So, remove that attribute or set it to False.
scrollbar.pack(side=tk.RIGHT, fill=tk.Y, expand=False)
tip: when debugging layout problems, the problems are easier to visualize when you temporarily give each widget a unique color. For example, set the canvas to one color, body to another, the instance of Scrollable to another, etc. This will let you see which parts are visible, which are growing or shrinking, which are inside the borders of others, etc.

Scrollbar in TKinter class is not interactive

I have a lot of Labels in a frame in TKinter. I would like a scrollbar to see all the labels that appear out of the screen. What I have currently tried does not work. Here is a MWE:
from tkinter import *
from tkinter import ttk
import tkinter.font as font
from tkinter import Tk
from PIL import Image, ImageTk
fontcolor = '#3a346f'
class SecurityProperties(Frame):
def __init__(self, master, *args, **kwargs):
super().__init__(master, *args, **kwargs)
# Set up scroll bar
self.main_frame = Frame(self)
self.main_frame.pack(fill=BOTH, expand=1)
self.my_canvas = Canvas(self.main_frame)
self.my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
self.my_scrollbar=ttk.Scrollbar(self.main_frame, orient=VERTICAL, command=self.my_canvas.yview)
self.my_scrollbar.pack(side=RIGHT, fill=Y)
self.my_canvas.configure(yscrollcommand=self.my_scrollbar.set)
self.my_canvas.bind('<Configure>', lambda e: self.my_canvas.configure(scrollregion = self.my_canvas.bbox("all")))
self.second_frame = Frame(self.my_canvas)
self.my_canvas.create_window((0,0), window=self.second_frame, anchor= "nw")
helv15 = font.Font(family="Helvetica",size=15,weight="bold")
self.UpperTextBox = Label(self.second_frame, bg = "white", relief = GROOVE, text = "Information", font = helv15, fg = fontcolor)
self.UpperTextBox.place(relheight = 0.15, relwidth = 0.8, relx = 0.1, rely = 0.1)
A scrollbar appears but is not interactive. Note the MWE has only one button, but the scrollbar does not work even when there are more labels that disappear off-screen. How can I make the scrollbar work?
You need to make sure that you update the scrollregion whenever you add or remove data to the canvas, or when the data on the canvas changes size. Your code only updates it when the canvas itself is resized.

tkinter background image in Frame

I want to put a background image in a Frame, this is the code that I'm trying to run without success.
import tkinter as tk
from tkinter import *
root = tk.Tk()
F1 = Frame(root)
F1.grid(row=0)
photo = PhotoImage(file="sfondo.png")
label = Label(F1, image=photo)
label.image = photo
label.place(x=0, y=0)
b = tk.Button(label, text="Start")
b.grid(row=8, column=8)
root.mainloop()
If I run the code as this, only a little point in the top left corner is displayed (the frame without nothing in, even if I placed the label inside of it). If I replace the label parent with root, it displays the button with a little part of the image as backgound (only the perimeter of the button is colored for a few pixels). However what I want is a full displayed background image in the frame where I can put the widgets that I want.
I tried to with the place method as this and PIL module
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
root = tk.Tk()
F1 = Frame(root)
F1.grid(row=0)
image = Image.open("sfondo.png")
render = ImageTk.PhotoImage(image)
img = tk.Label(F1, image=render)
img.image = render
img.place(x=0, y=40)
b = tk.Button(img, text="Start")
b.grid(row=8, column=8)
root.mainloop()
Here more or less I'm having the same problems, if I set the parent of the label to root, the button is displayed with the perimeter coloured.
If I set the parent to F1 nothing happens and in both cases if I set the parent as root and remove the button, the image is fully displayed.
But what I want is that the image is fully displayed in the frame and after diplay on the background image the widgets.
You could put an image on a Canvas, and then place a Button on that by putting it inside a Canvas window object which can hold any Tkinter widget.
Additional widgets can be added in a similar fashion, each inside its own Canvas window object (since they can hold only a single widget each). You can workaround that limitation by placing a Frame widget in the Canvas window, and then putting other widgets inside it.
Here's an example showing how to display a single Button:
from PIL import Image, ImageTk
import tkinter as tk
IMAGE_PATH = 'sfondo.png'
WIDTH, HEIGTH = 200, 200
root = tk.Tk()
root.geometry('{}x{}'.format(WIDTH, HEIGHT))
canvas = tk.Canvas(root, width=WIDTH, height=HEIGTH)
canvas.pack()
img = ImageTk.PhotoImage(Image.open(IMAGE_PATH).resize((WIDTH, HEIGTH), Image.ANTIALIAS))
canvas.background = img # Keep a reference in case this code is put in a function.
bg = canvas.create_image(0, 0, anchor=tk.NW, image=img)
# Put a tkinter widget on the canvas.
button = tk.Button(root, text="Start")
button_window = canvas.create_window(10, 10, anchor=tk.NW, window=button)
root.mainloop()
Screenshot:
Edit
While I don't know of a way to do it in Frame instead of a Canvas, you could derive your own Frame subclass to make adding multiple widgets easier. Here's what I mean:
from PIL import Image, ImageTk
import tkinter as tk
class BkgrFrame(tk.Frame):
def __init__(self, parent, file_path, width, height):
super(BkgrFrame, self).__init__(parent, borderwidth=0, highlightthickness=0)
self.canvas = tk.Canvas(self, width=width, height=height)
self.canvas.pack()
pil_img = Image.open(file_path)
self.img = ImageTk.PhotoImage(pil_img.resize((width, height), Image.ANTIALIAS))
self.bg = self.canvas.create_image(0, 0, anchor=tk.NW, image=self.img)
def add(self, widget, x, y):
canvas_window = self.canvas.create_window(x, y, anchor=tk.NW, window=widget)
return widget
if __name__ == '__main__':
IMAGE_PATH = 'sfondo.png'
WIDTH, HEIGTH = 350, 200
root = tk.Tk()
root.geometry('{}x{}'.format(WIDTH, HEIGTH))
bkrgframe = BkgrFrame(root, IMAGE_PATH, WIDTH, HEIGTH)
bkrgframe.pack()
# Put some tkinter widgets in the BkgrFrame.
button1 = bkrgframe.add(tk.Button(root, text="Start"), 10, 10)
button2 = bkrgframe.add(tk.Button(root, text="Continue"), 50, 10)
root.mainloop()
Result:
Update
It recently dawned on me that there actually is a simpler way to do this than creating a custom Frame subclass as shown in my previous edit above. The trick is to place() a Label with image on it in the center of the parent Frame — you are then free to use other geometry managers like pack() and grid() as you normally would — as illustrated in the sample code below. Not only is it less complicated, it's also a more "natural" way of adding widgets than needing to call a non-standard method such as add().
from PIL import Image, ImageTk
import tkinter as tk
IMAGE_PATH = 'sfondo.png'
WIDTH, HEIGHT = 250, 150
root = tk.Tk()
root.geometry('{}x{}'.format(WIDTH, HEIGHT))
# Display image on a Label widget.
img = ImageTk.PhotoImage(Image.open(IMAGE_PATH).resize((WIDTH, HEIGHT), Image.ANTIALIAS))
lbl = tk.Label(root, image=img)
lbl.img = img # Keep a reference in case this code put is in a function.
lbl.place(relx=0.5, rely=0.5, anchor='center') # Place label in center of parent.
# Add other tkinter widgets.
button = tk.Button(root, text="Start")
button.grid(row=0, column=0)
button = tk.Button(root, text="Continue")
button.grid(row=0, column=1, padx=10)
root.mainloop()
Result#2
P.S. You can download a copy of the sfondo.png background image from here.

A tkinter notebook with scrollbars if the contents are too large

I am trying to create an interface with tkinter. It should have a control panel on the left, and a set of 3 tabs on the right.
The tabs will show images, which may be too large for the screen, however the exact size will only be known after they have been dynamically created by the program. So I want to have a Notebook that expands to fill the top window, and if the image is too large for the notebook frame, scrollbars should appear to allow for all the image to be seen. I can't find a way to attach scrollbars to the notebook, so I have attached them to the canvases inside the notebook.
My code below expands the canvas to fit the image, but the scrollbar is useless as it stretches to fit the canvas, which is larger than the frame, and so can end up outside the window.
I think I want to set the scrollregion to the size of the containing frame. Dynamically changing scrollregion of a canvas in Tkinter seems to be related, but I can't work out how to apply that to my code:
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
class App(tk.Frame):
def __init__(self, parent, *args, **kwargs):
self.parent = parent
super().__init__(parent, *args, **kwargs)
self.pack(expand=True, fill=tk.BOTH)
self.inputframe = ttk.Frame(self)
self.inputframe.pack(side=tk.LEFT, expand=False, fill=tk.Y)
self.outputnotebook = ttk.Notebook(self)
self.outputnotebook.pack(side=tk.RIGHT, expand=True, fill=tk.BOTH)
self.build_inputframe()
self.build_outputnotebook()
def build_inputframe(self):
run_button = ttk.Button(self.inputframe, text="Run", command=self.draw)
run_button.grid(column=2, row=0, sticky=(tk.W, tk.E))
# rest of app...
def build_outputnotebook(self):
actnet_frame = ttk.Frame(self.outputnotebook)
critnet_frame = ttk.Frame(self.outputnotebook)
xscrollbar = ttk.Scrollbar(actnet_frame, orient=tk.HORIZONTAL)
xscrollbar.grid(row=1, column=0, sticky=tk.E + tk.W)
self.outputnotebook.add(
actnet_frame,
text="Tab 1",
sticky=tk.N + tk.S + tk.E + tk.W)
self.outputnotebook.add(critnet_frame, text="Tab 2")
self.actnet_canvas = tk.Canvas(actnet_frame, width=400, height=400,
xscrollcommand=xscrollbar.set)
self.actnet_canvas.grid(row=0, sticky=tk.N + tk.S + tk.E + tk.W)
xscrollbar.config(command=self.actnet_canvas.xview)
def draw(self):
act_image = Image.open('critnet.png') # image is 875 x 175
width, height = act_image.size
actphoto = ImageTk.PhotoImage(act_image)
self.actnet_canvas.delete("all")
self.actnet_canvas.create_image(0, 0, anchor=tk.NW, image=actphoto)
self.actnet_canvas.image = actphoto
self.actnet_canvas['scrollregion'] = (0, 0, width, height)
self.actnet_canvas['width'] = width
self.actnet_canvas['height'] = height
#do similar for other tabs.
root = tk.Tk()
root.geometry("800x600")
app = App(root)
app.mainloop()
The problem in your code is that you resize the canvas at the size of the picture, so the size of the canvas and of the scrollregion are the same. And it makes your canvas to big for your tab and your scrollbar useless.
I suppressed the lines
self.actnet_canvas['width'] = width
self.actnet_canvas['height'] = height
from the draw function and the scrollbar behaved as expected.
Edit: I had missed the other part of the question. To resize the canvas and scrollbar with the window, I added the following lines in build_outputnotebook:
actnet_frame.rowconfigure(0,weight=1)
actnet_frame.columnconfigure(0,weight=1)

Python Tkinter Scrollbar for entire window

Is there a way to add a scrollbar to my entire window without putting everything into a frame? I've set everything up with .grid, and I don't like the idea of wrapping a frame around everything.
root = Tk()
root.maxsize(900,600)
circus()#calls the function to set up everything
root.mainloop()
How to add scrollbars to full window in tkinter ?
here is the answer for python 3...
from tkinter import *
from tkinter import ttk
root = Tk()
root.title('Full Window Scrolling X Y Scrollbar Example')
root.geometry("1350x400")
# Create A Main frame
main_frame = Frame(root)
main_frame.pack(fill=BOTH,expand=1)
# Create Frame for X Scrollbar
sec = Frame(main_frame)
sec.pack(fill=X,side=BOTTOM)
# Create A Canvas
my_canvas = Canvas(main_frame)
my_canvas.pack(side=LEFT,fill=BOTH,expand=1)
# Add A Scrollbars to Canvas
x_scrollbar = ttk.Scrollbar(sec,orient=HORIZONTAL,command=my_canvas.xview)
x_scrollbar.pack(side=BOTTOM,fill=X)
y_scrollbar = ttk.Scrollbar(main_frame,orient=VERTICAL,command=my_canvas.yview)
y_scrollbar.pack(side=RIGHT,fill=Y)
# Configure the canvas
my_canvas.configure(xscrollcommand=x_scrollbar.set)
my_canvas.configure(yscrollcommand=y_scrollbar.set)
my_canvas.bind("<Configure>",lambda e: my_canvas.config(scrollregion= my_canvas.bbox(ALL)))
# Create Another Frame INSIDE the Canvas
second_frame = Frame(my_canvas)
# Add that New Frame a Window In The Canvas
my_canvas.create_window((0,0),window= second_frame, anchor="nw")
for thing in range(100):
Button(second_frame ,text=f"Button {thing}").grid(row=5,column=thing,pady=10,padx=10)
for thing in range(100):
Button(second_frame ,text=f"Button {thing}").grid(row=thing,column=5,pady=10,padx=10)
root.mainloop()
you might be able to set a scrollbarr to root.
scrollderoot = tkinter.Scrollbar(orient="vertical", command=root.yview)
scrollderoot.grid(column=5, row=0, sticky='ns', in_=root) #instead of number 5, set the column as the expected one for the scrollbar. Sticky ns will might be neccesary.
root.configure(yscrollcommand=scrollderoot.set)
Honestly i didn't tried this but "should" work. Good luck.
This approach uses no Frame objects and is different in that it creates a very large Canvas with Scrollbars and asks you for an image to display on it.
The screen is then set with self.root.wm_attributes("-fullscreen", 1)
and self.root.wm_attributes("-top", 1)
Press the Escape key or Alt-F4 to close.
import tkinter as tk
from tkinter import filedialog as fido
class BigScreen:
def __init__( self ):
self.root = tk.Tk()
self.root.rowconfigure(0, weight = 1)
self.root.columnconfigure(0, weight = 1)
w, h = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
self.canvas = tk.Canvas(self.root, scrollregion = f"0 0 {w*2} {h*2}")
self.canvas.grid(row = 0, column = 0, sticky = tk.NSEW)
self.makescroll(self.root, self.canvas )
self.imagename = fido.askopenfilename( title = "Pick Image to View" )
if self.imagename:
self.photo = tk.PhotoImage(file = self.imagename).zoom(2, 2)
self.window = self.canvas.create_image(
( 0, 0 ), anchor = tk.NW, image = self.photo)
self.root.bind("<Escape>", self.closer)
self.root.wm_attributes("-fullscreen", 1)
self.root.wm_attributes("-top", 1)
def makescroll(self, parent, thing):
v = tk.Scrollbar(parent, orient = tk.VERTICAL, command = thing.yview)
v.grid(row = 0, column = 1, sticky = tk.NS)
thing.config(yscrollcommand = v.set)
h = tk.Scrollbar(parent, orient = tk.HORIZONTAL, command = thing.xview)
h.grid(row = 1, column = 0, sticky = tk.EW)
thing.config(xscrollcommand = h.set)
def closer(self, ev):
self.root.destroy()
if __name__ == "__main__":
Big = BigScreen()
Big.root.mainloop()
My previous answer went well beyond the question asked so this is a cut-down version more accurately answers the question.
I did try the answer of Akash Shendage which didn't work for me out of the box. But with a few adjustments go it working.
#!/bin/env python3
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
root.title('Full Window Scrolling X Y Scrollbar Example')
root.geometry("1350x400")
# Create A Main frame
main_frame = tk.Frame(root)
main_frame.pack(fill=tk.BOTH,expand=1)
# Create Frame for X Scrollbar
sec = tk.Frame(main_frame)
sec.pack(fill=tk.X,side=tk.BOTTOM)
# Create A Canvas
my_canvas = tk.Canvas(main_frame)
my_canvas.pack(side=tk.LEFT,fill=tk.BOTH,expand=1)
# Add A Scrollbars to Canvas
x_scrollbar = ttk.Scrollbar(sec,orient=tk.HORIZONTAL,command=my_canvas.xview)
x_scrollbar.pack(side=tk.BOTTOM,fill=tk.X)
y_scrollbar = ttk.Scrollbar(main_frame,orient=tk.VERTICAL,command=my_canvas.yview)
y_scrollbar.pack(side=tk.RIGHT,fill=tk.Y)
# Configure the canvas
my_canvas.configure(xscrollcommand=x_scrollbar.set)
my_canvas.configure(yscrollcommand=y_scrollbar.set)
my_canvas.bind("<Configure>",lambda e: my_canvas.config(scrollregion= my_canvas.bbox(tk.ALL)))
# Create Another Frame INSIDE the Canvas
second_frame = tk.Frame(my_canvas)
# Add that New Frame a Window In The Canvas
my_canvas.create_window((0,0),window= second_frame, anchor="nw")
for thing in range(100):
tk.Button(second_frame ,text=f"Button {thing}").grid(row=5,column=thing,pady=10,padx=10)
for thing in range(100):
tk.Button(second_frame ,text=f"Button {thing}").grid(row=thing,column=5,pady=10,padx=10)
root.mainloop()
From the great effbot docs:
In Tkinter, the scrollbar is a separate widget that can be attached to
any widget that support the standard scrollbar interface. Such widgets
include:
the Listbox widget.
the Text widget.
the Canvas widget
the Entry widget
So, you cannot directly use a scrollbar in a Frame. It may be possible to create your own Frame sub-class that supports the scrollbar interface.
Out of the 4 widgets listed above, only one allows other widgets within it: the Canvas. You can use a Canvas to have scrollable content, but placing widgets within a Canvas does not use pack or grid, but uses explicit pixel locations (i.e. painting on the Canvas).
Here's a class, and some example usage, that uses the .place method to add a scrollbar for the whole window. You can create a Frame object, and place it at your desired (x, y) coordinates. Then, simply pass your Frame object in place of root in main.frame to create a scrollable window at your desired coordinates.
from tkinter import *
class ScrollableFrame:
"""A scrollable tkinter frame that will fill the whole window"""
def __init__ (self, master, width, height, mousescroll=0):
self.mousescroll = mousescroll
self.master = master
self.height = height
self.width = width
self.main_frame = Frame(self.master)
self.main_frame.pack(fill=BOTH, expand=1)
self.scrollbar = Scrollbar(self.main_frame, orient=VERTICAL)
self.scrollbar.pack(side=RIGHT, fill=Y)
self.canvas = Canvas(self.main_frame, yscrollcommand=self.scrollbar.set)
self.canvas.pack(expand=True, fill=BOTH)
self.scrollbar.config(command=self.canvas.yview)
self.canvas.bind(
'<Configure>',
lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
)
self.frame = Frame(self.canvas, width=self.width, height=self.height)
self.frame.pack(expand=True, fill=BOTH)
self.canvas.create_window((0,0), window=self.frame, anchor="nw")
self.frame.bind("<Enter>", self.entered)
self.frame.bind("<Leave>", self.left)
def _on_mouse_wheel(self,event):
self.canvas.yview_scroll(-1 * int((event.delta / 120)), "units")
def entered(self,event):
if self.mousescroll:
self.canvas.bind_all("<MouseWheel>", self._on_mouse_wheel)
def left(self,event):
if self.mousescroll:
self.canvas.unbind_all("<MouseWheel>")
# Example usage
obj = ScrollableFrame(
master,
height=300, # Total required height of canvas
width=400 # Total width of master
)
objframe = obj.frame
# use objframe as the main window to make widget

Categories

Resources