I want to create a simple GUI image labeler tool in Tkinter for my research project. Currently, I have working code that can load images from the directory and allows me to draw multiple bounding boxes. I want to modify the code such that I can resize the rectangle BB using a mouse when I click on it. I have searched online and couldn't find any resources to do that. Can someone help me understand how to do that?
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from tkinter import ttk
from PIL import Image, ImageTk
import os
import glob
import random
# colors for the bboxes
COLORS = ['red', 'blue','pink', 'cyan', 'green', 'black']
# image sizes for the examples
SIZE = 256, 256
class LabelTool():
def __init__(self, master):
# set up the main frame
self.parent = master
self.parent.title("LabelTool")
self.frame = Frame(self.parent)
self.frame.pack(fill=BOTH, expand=1)
self.parent.resizable(width = FALSE, height = FALSE)
# initialize global state
self.imageDir = ''
self.imageList= []
self.egDir = ''
self.egList = []
self.outDir = ''
self.cur = 0
self.total = 0
self.category = 0
self.imagename = ''
self.labelfilename = ''
self.tkimg = None
self.currentLabelclass = ''
self.cla_can_temp = []
self.classcandidate_filename = 'class.txt'
# initialize mouse state
self.STATE = {}
self.STATE['click'] = 0
self.STATE['x'], self.STATE['y'] = 0, 0
# reference to bbox
self.bboxIdList = []
self.bboxId = None
self.bboxList = []
self.hl = None
self.vl = None
self.srcDirBtn = Button(self.frame, text="Image input folder", command=self.selectSrcDir)
self.srcDirBtn.grid(row=0, column=0)
# input image dir entry
self.svSourcePath = StringVar()
self.entrySrc = Entry(self.frame, textvariable=self.svSourcePath)
self.entrySrc.grid(row=0, column=1, sticky=W+E)
self.svSourcePath.set(os.getcwd())
# load button
self.ldBtn = Button(self.frame, text="Load Dir", command=self.loadDir)
self.ldBtn.grid(row=0, column=2, rowspan=2, columnspan=2, padx=2, pady=2, ipadx=5, ipady=5)
# label file save dir button
self.desDirBtn = Button(self.frame, text="Label output folder", command=self.selectDesDir)
self.desDirBtn.grid(row=1, column=0)
# label file save dir entry
self.svDestinationPath = StringVar()
self.entryDes = Entry(self.frame, textvariable=self.svDestinationPath)
self.entryDes.grid(row=1, column=1, sticky=W+E)
self.svDestinationPath.set(os.path.join(os.getcwd(),"Labels"))
# main panel for labeling
self.mainPanel = Canvas(self.frame, cursor='tcross')
self.mainPanel.bind("<Button-1>", self.mouseClick)
self.mainPanel.bind("<Motion>", self.mouseMove)
self.mainPanel.grid(row = 2, column = 1, rowspan = 4, sticky = W+N)
# showing bbox info & delete bbox
self.lb1 = Label(self.frame, text = 'Bounding boxes:')
self.lb1.grid(row = 3, column = 2, sticky = W+N)
self.listbox = Listbox(self.frame, width = 22, height = 12)
self.listbox.grid(row = 4, column = 2, sticky = N+S)
# control panel for image navigation
self.ctrPanel = Frame(self.frame)
self.ctrPanel.grid(row = 6, column = 1, columnspan = 2, sticky = W+E)
self.progLabel = Label(self.ctrPanel, text = "Progress: / ")
self.progLabel.pack(side = LEFT, padx = 5)
self.tmpLabel = Label(self.ctrPanel, text = "Go to Image No.")
self.tmpLabel.pack(side = LEFT, padx = 5)
self.idxEntry = Entry(self.ctrPanel, width = 5)
self.idxEntry.pack(side = LEFT)
# display mouse position
self.disp = Label(self.ctrPanel, text='')
self.disp.pack(side = RIGHT)
self.frame.columnconfigure(1, weight = 1)
self.frame.rowconfigure(4, weight = 1)
def selectSrcDir(self):
path = filedialog.askdirectory(title="Select image source folder", initialdir=self.svSourcePath.get())
self.svSourcePath.set(path)
return
def selectDesDir(self):
path = filedialog.askdirectory(title="Select label output folder", initialdir=self.svDestinationPath.get())
self.svDestinationPath.set(path)
return
def loadDir(self):
self.parent.focus()
# get image list
#self.imageDir = os.path.join(r'./Images', '%03d' %(self.category))
self.imageDir = self.svSourcePath.get()
if not os.path.isdir(self.imageDir):
messagebox.showerror("Error!", message = "The specified dir doesn't exist!")
return
extlist = ["*.JPEG", "*.jpeg", "*JPG", "*.jpg", "*.PNG", "*.png", "*.BMP", "*.bmp"]
for e in extlist:
filelist = glob.glob(os.path.join(self.imageDir, e))
self.imageList.extend(filelist)
#self.imageList = glob.glob(os.path.join(self.imageDir, '*.JPEG'))
if len(self.imageList) == 0:
print('No .JPEG images found in the specified dir!')
return
# default to the 1st image in the collection
self.cur = 1
self.total = len(self.imageList)
# set up output dir
#self.outDir = os.path.join(r'./Labels', '%03d' %(self.category))
self.outDir = self.svDestinationPath.get()
if not os.path.exists(self.outDir):
os.mkdir(self.outDir)
self.loadImage()
print('%d images loaded from %s' %(self.total, self.imageDir))
def loadImage(self):
# load image
imagepath = self.imageList[self.cur - 1]
self.img = Image.open(imagepath)
size = self.img.size
self.factor = max(size[0]/1000, size[1]/1000., 1.)
self.img = self.img.resize((int(size[0]/self.factor), int(size[1]/self.factor)))
self.tkimg = ImageTk.PhotoImage(self.img)
self.mainPanel.config(width = max(self.tkimg.width(), 400), height = max(self.tkimg.height(), 400))
self.mainPanel.create_image(0, 0, image = self.tkimg, anchor=NW)
self.progLabel.config(text = "%04d/%04d" %(self.cur, self.total))
# load labels
self.clearBBox()
#self.imagename = os.path.split(imagepath)[-1].split('.')[0]
fullfilename = os.path.basename(imagepath)
self.imagename, _ = os.path.splitext(fullfilename)
labelname = self.imagename + '.txt'
self.labelfilename = os.path.join(self.outDir, labelname)
bbox_cnt = 0
if os.path.exists(self.labelfilename):
with open(self.labelfilename) as f:
for (i, line) in enumerate(f):
if i == 0:
bbox_cnt = int(line.strip())
continue
#tmp = [int(t.strip()) for t in line.split()]
tmp = line.split()
tmp[0] = int(int(tmp[0])/self.factor)
tmp[1] = int(int(tmp[1])/self.factor)
tmp[2] = int(int(tmp[2])/self.factor)
tmp[3] = int(int(tmp[3])/self.factor)
self.bboxList.append(tuple(tmp))
color_index = (len(self.bboxList)-1) % len(COLORS)
tmpId = self.mainPanel.create_rectangle(tmp[0], tmp[1], \
tmp[2], tmp[3], \
width = 2, \
outline = COLORS[color_index])
#outline = COLORS[(len(self.bboxList)-1) % len(COLORS)])
self.bboxIdList.append(tmpId)
self.listbox.insert(END, '%s : (%d, %d) -> (%d, %d)' %(tmp[4], tmp[0], tmp[1], tmp[2], tmp[3]))
self.listbox.itemconfig(len(self.bboxIdList) - 1, fg = COLORS[color_index])
#self.listbox.itemconfig(len(self.bboxIdList) - 1, fg = COLORS[(len(self.bboxIdList) - 1) % len(COLORS)])
def mouseClick(self, event):
if self.STATE['click'] == 0:
self.STATE['x'], self.STATE['y'] = event.x, event.y
else:
x1, x2 = min(self.STATE['x'], event.x), max(self.STATE['x'], event.x)
y1, y2 = min(self.STATE['y'], event.y), max(self.STATE['y'], event.y)
self.bboxList.append((x1, y1, x2, y2, self.currentLabelclass))
self.bboxIdList.append(self.bboxId)
self.bboxId = None
self.listbox.insert(END, '%s : (%d, %d) -> (%d, %d)' %(self.currentLabelclass, x1, y1, x2, y2))
self.listbox.itemconfig(len(self.bboxIdList) - 1, fg = COLORS[(len(self.bboxIdList) - 1) % len(COLORS)])
self.STATE['click'] = 1 - self.STATE['click']
def mouseMove(self, event):
self.disp.config(text = 'x: %d, y: %d' %(event.x, event.y))
if self.tkimg:
if self.hl:
self.mainPanel.delete(self.hl)
self.hl = self.mainPanel.create_line(0, event.y, self.tkimg.width(), event.y, width = 2)
if self.vl:
self.mainPanel.delete(self.vl)
self.vl = self.mainPanel.create_line(event.x, 0, event.x, self.tkimg.height(), width = 2)
if 1 == self.STATE['click']:
if self.bboxId:
self.mainPanel.delete(self.bboxId)
COLOR_INDEX = len(self.bboxIdList) % len(COLORS)
self.bboxId = self.mainPanel.create_rectangle(self.STATE['x'], self.STATE['y'], \
event.x, event.y, \
width = 2, \
outline = COLORS[len(self.bboxList) % len(COLORS)])
def setClass(self):
self.currentLabelclass = self.classcandidate.get()
print('set label class to : %s' % self.currentLabelclass)
if __name__ == '__main__':
root = Tk()
tool = LabelTool(root)
root.resizable(width = True, height = True)
root.mainloop()
That's hardly "minimal" ... it's still over 200 lines long. I don't want to sort through it but I'll make a minimal example to show you how to bind to a canvas item:
import tkinter as tk
from functools import partial
class DrawShapes(tk.Canvas):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
image = self.create_rectangle(0, 0, 400, 300, width=5, fill='green')
self.tag_bind(image, '<Button-1>', self.on_click)
self.tag_bind(image, '<Button1-Motion>', self.on_motion)
def on_click(self, event):
"""fires when user clicks on the background ... creates a new rectangle"""
self.start = event.x, event.y
self.current = self.create_rectangle(*self.start, *self.start, width=5)
self.tag_bind(self.current, '<Button-1>', partial(self.on_click_rectangle, self.current))
self.tag_bind(self.current, '<Button1-Motion>', self.on_motion)
def on_click_rectangle(self, tag, event):
"""fires when the user clicks on a rectangle ... edits the clicked on rectange"""
self.current = tag
x1, y1, x2, y2 = self.coords(tag)
if abs(event.x-x1) < abs(event.x-x2):
# opposing side was grabbed; swap the anchor and mobile side
x1, x2 = x2, x1
if abs(event.y-y1) < abs(event.y-y2):
y1, y2 = y2, y1
self.start = x1, y1
def on_motion(self, event):
"""fires when the user drags the mouse ... resizes currently active rectangle"""
self.coords(self.current, *self.start, event.x, event.y)
def main():
c = DrawShapes()
c.pack()
c.mainloop()
if __name__ == '__main__':
main()
Related
Thanks to lots of help in Drag and drop the object in Tkinter UI, I could manage to draw three square that are draggable.
Now I am trying to draw 3 lines between each squares and I cannot find way to enable it. What I tried is following :
from tkinter import *
window = Tk()
window.state('zoomed')
window.configure(bg = 'white')
def drag(event):
new_x = event.x_root - window.winfo_rootx()
new_y = event.y_root - window.winfo_rooty()
event.widget.place(x=new_x, y=new_y,anchor=CENTER)
card = Canvas(window, width=10, height=10, bg='red1')
card.place(x=300, y=600,anchor=CENTER)
card.bind("<B1-Motion>", drag)
another_card = Canvas(window, width=10, height=10, bg='red2')
another_card.place(x=600, y=600,anchor=CENTER)
another_card.bind("<B1-Motion>", drag)
third_card = Canvas(window, width=10, height=10, bg='red3')
third_card.place(x=600, y=600,anchor=CENTER)
third_card.bind("<B1-Motion>", drag)
def line(x1, y1, x2, y2):
print(x1, y1, x2, y2)
Canvas.create_line(x1, y1, x2, y2, fill="green")
coor_1 = canvas.coords(card)
coor_2 = canvas.coords(another_card)
line(coor_1[0],coor_1[1],coor_1[0],coor_2[1])
window.mainloop()
It didn't work and I don't think it will work since this code does not catch the change occurred by dragging object, But I cannot guess how to code since I do not understand how the event function works completely. How should I make a code for it ?
for the purpose of self-study:
import tkinter as tk
window = tk.Tk()
window.state('zoomed')
class DragAndDropArea(tk.Canvas):
def __init__(self,master, **kwargs):
tk.Canvas.__init__(self,master, **kwargs)
self.active = None
card_I = self.draw_card(300,600, 100,100, 'red1')
card_II = self.draw_card(600,600, 100,100, 'red2')
card_III = self.draw_card(400,400, 100,100, 'red3')
self.bind_tention(card_I,card_III)
self.bind_tention(card_I,card_II)
self.bind_tention(card_III,card_II)
self.bind('<ButtonPress-1>', self.get_item)
self.bind('<B1-Motion>',self.move_active)
self.bind('<ButtonRelease-1>', self.set_none)
def set_none(self,event):
self.active = None
def get_item(self,event):
try:
item = self.find_withtag('current')
self.active = item[0]
except IndexError:
print('no item was clicked')
def move_active(self,event):
if self.active != None:
coords = self.coords(self.active)
width = coords[2] - coords[0] #x2-x1
height= coords[1] - coords[3] #y1-y2
position = coords[0],coords[1]#x1,y1
x1 = event.x - width/2
y1 = event.y - height/2
x2 = event.x + width/2
y2 = event.y + height/2
self.coords(self.active, x1,y1, x2,y2)
try:
self.update_tention(self.active)
except IndexError:
print('no tentions found')
def update_tention(self, tag):
tentions = self.find_withtag(f'card {tag}')
for tention in tentions:
bounded_cards = self.gettags(tention)
card = bounded_cards[0].split()[-1]
card2= bounded_cards[1].split()[-1]
x1,y1 = self.get_mid_point(card)
x2,y2 = self.get_mid_point(card2)
self.coords(tention, x1,y1, x2,y2)
self.lower(tention)
def draw_card(self, x,y, width,height, color):
x1,y1 = x,y
x2,y2 = x+width,y+height
reference = self.create_rectangle(x1,y1,x2,y2,
fill = color)
return reference
def bind_tention(self, card, another_card):
x1,y1 = self.get_mid_point(card)
x2,y2 = self.get_mid_point(another_card)
tag_I = f'card {card}'
tag_II= f'card {another_card}'
reference = self.create_line(x1,y1,x2,y2, fill='green',
tags=(tag_I,tag_II))
self.lower(reference)
def get_mid_point(self, card):
coords = self.coords(card)
width = coords[2] - coords[0] #x2-x1
height= coords[1] - coords[3] #y1-y2
position = coords[0],coords[1]#x1,y1
mid_x = position[0] + width/2
mid_y = position[1] - height/2
return mid_x,mid_y
area = DragAndDropArea(window, bg='white')
area.pack(fill='both',expand=1)
window.mainloop()
I am writing a program in python tkinter that allows you to select certain areas in the image. This image can be zoomed and dragged inside a Canvas. But the problem is that I can't get correct coordinates of the selections and extract thumbnails from original images using the small one.
Here is my code and a screenshot:
from tkinter import *
from tkinter import ttk
from tkinter import messagebox as mb
import glob
import os
from PIL import Image, ImageTk
import cv2
from src.lsh_utils import get_lsh, query_lsh
from src.io_utils import get_config
COLORS = ['red', 'blue', 'olive', 'teal', 'cyan', 'green', 'black']
CONFIG = get_config('conf.json')
class AutoScrollbar(ttk.Scrollbar):
''' A scrollbar that hides itself if it not needed.
Works only if you use the grid geometry manager '''
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
self.grid_remove()
else:
self.grid()
ttk.Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise TclError('Cannot use pack with this widget')
def place(self, **kw):
raise TclError('Cannot use place with this widget')
class Zoom_Advanced(ttk.Frame):
''' Advanced zoom of the image '''
def __init__(self, mainframe, path):
''' Initialize the main Frame '''
ttk.Frame.__init__(self, master=mainframe)
self.master.title('Zoom with mouse wheel')
# Vertical and horizontal scrollbars for canvas
vbar = AutoScrollbar(self.master, orient='vertical')
hbar = AutoScrollbar(self.master, orient='horizontal')
vbar.grid(row=0, column=1, sticky='ns', rowspan=4)
hbar.grid(row=1, column=0, sticky='we')
# Create canvas and put image on it
self.canvas = Canvas(self.master, highlightthickness=0,
xscrollcommand=hbar.set, yscrollcommand=vbar.set)
self.canvas.grid(row=0, column=0, sticky='nswe')
self.canvas.update() # wait till canvas is created
vbar.configure(command=self.scroll_y) # bind scrollbars to the canvas
hbar.configure(command=self.scroll_x)
# Make the canvas expandable
self.master.rowconfigure(0, weight=1)
self.master.columnconfigure(0, weight=1)
# Bind events to the Canvas
self.canvas.bind('<Configure>', self.show_image) # canvas is resized
self.canvas.bind('<Button-3>', self.move_from)
self.canvas.bind("<Button-1>", self.mouseClick)
self.canvas.bind('<B3-Motion>', self.move_to)
self.canvas.bind("<Motion>", self.mouseMove)
self.canvas.bind('<MouseWheel>', self.wheel) # with Windows and MacOS, but not Linux
self.canvas.bind('<Button-5>', self.wheel) # only with Linux, wheel scroll down
self.canvas.bind('<Button-4>', self.wheel) # only with Linux, wheel scroll up
self.master.bind("<Escape>", self.cancelBBox) # press <Espace> to cancel current bbox
self.master.bind("s", self.cancelBBox)
self.master.bind("a", self.prevImage) # press 'a' to go backforward
self.master.bind("d", self.nextImage) # press 'd' to go forward
self.side_container = Frame(self.master)
self.side_container.grid_rowconfigure(0, weight=1)
self.side_container.grid_columnconfigure(0, weight=1)
self.side_container.grid(row=0, column=2, sticky='nse')
self.imscale = 1.0 # scale for the canvaas image
self.delta = 1.3 # zoom magnitude
self.lb1 = Label(self.side_container, text='Bounding boxes:')
self.lb1.grid(row=0, column=0, sticky='nwe')
self.listbox = Listbox(self.side_container)
self.listbox.grid(row=1, column=0, sticky='nwe')
self.btnDel = Button(self.side_container, text='Delete', command=self.delBBox)
self.btnDel.grid(row=2, column=0, sticky='nwe')
self.btnClear = Button(self.side_container, text='ClearAll', command=self.clearBBox)
self.btnClear.grid(row=3, column=0, sticky='nwe')
# control panel for image navigation
self.ctrPanel = Frame(self.side_container)
self.ctrPanel.grid(row=4, column=0, columnspan=2, sticky='we')
self.prevBtn = Button(self.ctrPanel, text='<< Prev', width=10, command=self.prevImage)
self.prevBtn.pack(side=LEFT, padx=5, pady=3)
self.nextBtn = Button(self.ctrPanel, text='Next >>', width=10, command=self.nextImage)
self.nextBtn.pack(side=LEFT, padx=5, pady=3)
self.progLabel = Label(self.ctrPanel, text="Progress: / ")
self.progLabel.pack(side=LEFT, padx=5)
self.tmpLabel = Label(self.ctrPanel, text="Go to Image No.")
self.tmpLabel.pack(side=LEFT, padx=5)
self.idxEntry = Entry(self.ctrPanel, width=5)
self.idxEntry.pack(side=LEFT)
self.goBtn = Button(self.ctrPanel, text='Go', command=self.gotoImage)
self.goBtn.pack(side=LEFT)
self.runBtn = Button(self.ctrPanel, text='Run', command=self.run)
self.runBtn.pack(side=LEFT, padx=5, pady=3)
self.imageDir = ''
self.imageList = []
self.egDir = ''
self.egList = []
self.outDir = ''
self.cur = 0
self.total = 0
self.category = 0
self.imagename = ''
self.labelfilename = ''
self.tkimg = None
self.cla_can_temp = []
self.detection_images_path = CONFIG.get('DETECTIONS_PATH', 'data\\detections')
self.orig_images_path = CONFIG.get('IMAGE_DIR')
self.viewer = None
self._new_window = None
# initialize mouse state
self.STATE = {}
self.STATE['click'] = 0
self.STATE['x'], self.STATE['y'] = 0, 0
# reference to bbox
self.bboxIdList = []
self.bboxId = None
self.bboxList = []
self.hl = None
self.vl = None
self.disp = Label(self.ctrPanel, text='')
self.disp.pack(side=RIGHT)
self.loadDir()
# self.show_image()
def scroll_y(self, *args, **kwargs):
''' Scroll canvas vertically and redraw the image '''
self.canvas.yview(*args, **kwargs) # scroll vertically
self.show_image() # redraw the image
def scroll_x(self, *args, **kwargs):
''' Scroll canvas horizontally and redraw the image '''
self.canvas.xview(*args, **kwargs) # scroll horizontally
self.show_image() # redraw the image
def move_from(self, event):
''' Remember previous coordinates for scrolling with the mouse '''
self.canvas.scan_mark(event.x, event.y)
def move_to(self, event):
''' Drag (move) canvas to the new position '''
self.canvas.scan_dragto(event.x, event.y, gain=1)
self.show_image() # redraw the image
def wheel(self, event):
''' Zoom with mouse wheel '''
x = self.canvas.canvasx(event.x)
y = self.canvas.canvasy(event.y)
bbox = self.canvas.bbox(self.container) # get image area
if bbox[0] < x < bbox[2] and bbox[1] < y < bbox[3]: pass # Ok! Inside the image
else: return # zoom only inside image area
scale = 1.0
# Respond to Linux (event.num) or Windows (event.delta) wheel event
if event.num == 5 or event.delta == -120: # scroll down
i = min(self.width, self.height)
if int(i * self.imscale) < 30: return # image is less than 30 pixels
self.imscale /= self.delta
scale /= self.delta
if event.num == 4 or event.delta == 120: # scroll up
i = min(self.canvas.winfo_width(), self.canvas.winfo_height())
if i < self.imscale: return # 1 pixel is bigger than the visible area
self.imscale *= self.delta
scale *= self.delta
self.canvas.scale('all', x, y, scale, scale) # rescale all canvas objects
self.show_image()
def show_image(self, event=None):
''' Show image on the Canvas '''
bbox1 = self.canvas.bbox(self.container) # get image area
# Remove 1 pixel shift at the sides of the bbox1
bbox1 = (bbox1[0] + 1, bbox1[1] + 1, bbox1[2] - 1, bbox1[3] - 1)
bbox2 = (self.canvas.canvasx(0), # get visible area of the canvas
self.canvas.canvasy(0),
self.canvas.canvasx(self.canvas.winfo_width()),
self.canvas.canvasy(self.canvas.winfo_height()))
bbox = [min(bbox1[0], bbox2[0]), min(bbox1[1], bbox2[1]), # get scroll region box
max(bbox1[2], bbox2[2]), max(bbox1[3], bbox2[3])]
print(bbox)
if bbox[0] == bbox2[0] and bbox[2] == bbox2[2]: # whole image in the visible area
bbox[0] = bbox1[0]
bbox[2] = bbox1[2]
if bbox[1] == bbox2[1] and bbox[3] == bbox2[3]: # whole image in the visible area
bbox[1] = bbox1[1]
bbox[3] = bbox1[3]
print(bbox2, bbox1)
self.canvas.configure(scrollregion=bbox) # set scroll region
x1 = max(bbox2[0] - bbox1[0], 0) # get coordinates (x1,y1,x2,y2) of the image tile
y1 = max(bbox2[1] - bbox1[1], 0)
x2 = min(bbox2[2], bbox1[2]) - bbox1[0]
y2 = min(bbox2[3], bbox1[3]) - bbox1[1]
print(x1, y1, x2, y2)
if int(x2 - x1) > 0 and int(y2 - y1) > 0: # show image if it in the visible area
x = min(int(x2 / self.imscale), self.width) # sometimes it is larger on 1 pixel...
y = min(int(y2 / self.imscale), self.height) # ...and sometimes not
print(x, y)
image = self.image.crop((int(x1 / self.imscale), int(y1 / self.imscale), x, y))
self.imagetk = ImageTk.PhotoImage(image.resize((int(x2 - x1), int(y2 - y1))))
imageid = self.canvas.create_image(max(bbox2[0], bbox1[0]), max(bbox2[1], bbox1[1]),
anchor='nw', image=self.imagetk)
self.canvas.lower(imageid) # set image into background
self.canvas.imagetk = self.imagetk # keep an extra reference to prevent garbage-collection
def run(self):
labels = self._compare_labels()
lsh = get_lsh(CONFIG.get('LSH_DATASET'))
if not labels:
return
for file, bboxes in labels.items():
im = cv2.imread(file)
h, w, _ = im.shape
print(w, h)
rois = []
for box in bboxes:
x1 = int(int(box[0])/600*w)
y1 = int(int(box[1])/800*h)
x2 = int(int(box[2])/600*w)
y2 = int(int(box[3])/800*h)
roi = im[y1:y2, x1:x2].copy()
print(file, [n[0][1] for n in query_lsh(lsh, roi)])
# cv2.imshow(str(box), roi)
# cv2.waitKey()
# def _update_labels_boxes(self, w, h):
# for i, bbox in enumerate(self.listbox):
# x1 = int(int(bbox[0]) / 768 * w)
# y1 = int(int(bbox[1]) / 768 * h)
# x2 = int(int(bbox[2]) / 768 * w)
# y2 = int(int(bbox[3]) / 768 * h)
#
def _compare_labels(self):
label_dict = dict()
if not self.imageDir:
return None
for label_file in glob.glob(os.path.join(self.imageDir, '*.txt')):
with open(label_file, 'r') as f:
filename = ''.join([os.path.splitext(label_file)[0], '.jpg'])
label_dict[filename] = [tuple(l.split()) for l in f.readlines()]
return label_dict
def loadDir(self, dbg=False):
# get image list
self.imageDir = self.orig_images_path
# print self.imageDir
# print self.category
self.imageList = glob.glob(os.path.join(self.imageDir, '*.JPG'))
print(self.imageList)
if len(self.imageList) == 0:
print('No .JPG images found in the specified dir!')
return
# default to the 1st image in the collection
self.cur = 1
self.total = len(self.imageList)
# set up output dir
self.outDir = self.imageDir
if not os.path.exists(self.outDir):
os.mkdir(self.outDir)
self.loadImage()
print('%d images loaded from %s' % (self.total, self.orig_images_path))
def new_window(self, path):
self.newWindow = Toplevel(self.master)
# frame = Frame(self.newWindow)
self.new_panel = Canvas(self.newWindow, cursor='tcross')
self.new_img = ImageTk.PhotoImage(Image.open(path).resize((600, 800)))
self.new_panel.pack()
self.new_panel.config(width=max(self.new_img.width(), 400), height=max(self.new_img.height(), 400))
self.new_panel.create_image(0, 0, image=self.new_img, anchor=NW)
return self.new_panel
def loadImage(self):
# load image
imagepath = self.imageList[self.cur - 1]
self.img = Image.open(imagepath).resize((600, 800))
detect_image_path = os.path.join(self.detection_images_path, 'detect_'+os.path.basename(imagepath))
if not os.path.exists(detect_image_path):
mb.showerror(f'image {detect_image_path} doesn\' exists')
self.nextImage(save=False)
self.new_window(detect_image_path)
# cv2.imshow(f'{detect_image_path}', detect_image_path)
self.image = Image.open(path) # open image
self.width, self.height = self.image.size
# Put image into container rectangle and use it to set proper coordinates to the image
self.container = self.canvas.create_rectangle(0, 0, self.width, self.height, width=0)
self.show_image()
# load labels
self.clearBBox()
self.imagename = os.path.split(imagepath)[-1].split('.')[0]
labelname = self.imagename + '.txt'
self.labelfilename = os.path.join(self.outDir, labelname)
if os.path.exists(self.labelfilename):
with open(self.labelfilename) as f:
for (i, line) in enumerate(f):
# tmp = [int(t.strip()) for t in line.split()]
tmp = line.split()
self.bboxList.append(tuple(tmp))
tmpId = self.canvas.create_rectangle(int(tmp[0]), int(tmp[1]),
int(tmp[2]), int(tmp[3]),
width=2,
outline=COLORS[(len(self.bboxList) - 1) % len(COLORS)])
# print tmpId
self.bboxIdList.append(tmpId)
self.listbox.insert(END, '(%d, %d) -> (%d, %d)' % (int(tmp[0]), int(tmp[1]),
int(tmp[2]), int(tmp[3])))
self.listbox.itemconfig(len(self.bboxIdList) - 1,
fg=COLORS[(len(self.bboxIdList) - 1) % len(COLORS)])
def saveImage(self):
if self.newWindow:
self.newWindow.destroy()
with open(self.labelfilename, 'w') as f:
for bbox in self.bboxList:
f.write(' '.join(map(str, bbox)) + '\n')
print('Image No. %d saved' % (self.cur))
def mouseClick(self, event):
new_x, new_y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
if self.STATE['click'] == 0:
self.STATE['x'], self.STATE['y'] = new_x, new_y
else:
x1, x2 = min(self.STATE['x'], new_x), max(self.STATE['x'], new_x)
y1, y2 = min(self.STATE['y'], new_y), max(self.STATE['y'], new_y)
x, y = int(x2 / self.imscale), int(y2 / self.imscale)
print(self.imscale, (int(x1 / self.imscale), int(y1 / self.imscale), x, y))
im = self.image.crop((int(x1 / self.imscale), int(y1 / self.imscale), x, y))
im.show()
self.bboxList.append((int(x1 / self.imscale), int(y1 / self.imscale), x, y))
self.bboxIdList.append(self.bboxId)
self.bboxId = None
self.listbox.insert(END, '(%d, %d) -> (%d, %d)' % (x1, y1, x2, y2))
self.listbox.itemconfig(len(self.bboxIdList) - 1, fg=COLORS[(len(self.bboxIdList) - 1) % len(COLORS)])
self.STATE['click'] = 1 - self.STATE['click']
def mouseMove(self, event):
new_x, new_y = int(self.canvas.canvasx(event.x)), int(self.canvas.canvasy(event.y))
self.disp.config(text='x: %d, y: %d' % (new_x, new_y))
if self.canvas:
if self.hl:
self.canvas.delete(self.hl)
self.hl = self.canvas.create_line(0, new_y, self.canvas['width'], new_y, width=2)
if self.vl:
self.canvas.delete(self.vl)
self.vl = self.canvas.create_line(new_x, 0, new_x, self.canvas['height'], width=2)
if 1 == self.STATE['click']:
if self.bboxId:
self.canvas.delete(self.bboxId)
self.bboxId = self.canvas.create_rectangle(self.STATE['x'], self.STATE['y'],
new_x, new_y,
width=2,
outline=COLORS[len(self.bboxList) % len(COLORS)])
def cancelBBox(self, event):
if 1 == self.STATE['click']:
if self.bboxId:
self.canvas.delete(self.bboxId)
self.bboxId = None
self.STATE['click'] = 0
def delBBox(self):
sel = self.listbox.curselection()
if len(sel) != 1:
return
idx = int(sel[0])
self.canvas.delete(self.bboxIdList[idx])
self.bboxIdList.pop(idx)
self.bboxList.pop(idx)
self.listbox.delete(idx)
def clearBBox(self):
for idx in range(len(self.bboxIdList)):
self.canvas.delete(self.bboxIdList[idx])
self.listbox.delete(0, len(self.bboxList))
self.bboxIdList = []
self.bboxList = []
def prevImage(self, event=None):
self.saveImage()
if self.cur > 1:
self.cur -= 1
self.loadImage()
def nextImage(self, event=None, save=True):
if save:
self.saveImage()
if self.cur < self.total:
self.cur += 1
self.loadImage()
def gotoImage(self):
idx = int(self.idxEntry.get())
if 1 <= idx <= self.total:
self.saveImage()
self.cur = idx
self.loadImage()
path = 'data\\detections\\detect_1.jpg' # place path to your image here
root = Tk()
root.geometry('1280x720')
app = Zoom_Advanced(root, path=path)
root.mainloop()
I think the solution is in def MouseClick and in show_image. My thoughts is to use the same methods of extracting a tile (or a bbox) from original image as in show_image.
I tried to fo that but I didn't get any results. I don't understand how can I do that so I'm searching for the help here.
I did that with this code, where self.container is a rectangle around image with its width and height and self.imscale is scale of image.
...
new_x, new_y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
if self.STATE['click'] == 0:
self.STATE['x'], self.STATE['y'] = new_x, new_y
else:
x1, x2 = min(self.STATE['x'], new_x), max(self.STATE['x'], new_x)
y1, y2 = min(self.STATE['y'], new_y), max(self.STATE['y'], new_y)
self.canvas.create_text((x1 + x2) // 2, (y1 + y2) // 2, text=self.bbox_num)
bbox = self.canvas.bbox(self.container)
x1 = int((x1 - bbox[0]) / self.imscale)
y1 = int((y1 - bbox[1]) / self.imscale)
x2 = int((x2 - bbox[0]) / self.imscale)
y2 = int((y2 - bbox[1]) / self.imscale)
from tkinter import *
from PIL import Image, ImageTk
import time
schermata = Tk()
screen_width = schermata.winfo_screenwidth()
screen_height = schermata.winfo_screenheight()
indice = 0
schermata.iconbitmap("immagini\icona.ico")
screen_resolution = str(screen_width)+'x'+str(screen_height)
large_font = ('Verdana',30)
schermata.geometry(screen_resolution)
schermata.title("Jovan's RPG")
class GUI(Frame):
def __init__(self, master):
super(GUI, self).__init__(master)
self.pack()
self.bg()
self.immagine()
self.testo()
self.statistiche()
self.inserimenti()
def bg(self):
load = Image.open("immagini\\background.png")
render = ImageTk.PhotoImage(load)
img = Label(schermata, image = render)
img.image = render
img.pack()
def immagine(self):
load = Image.open("immagini\\dn.png")
render = ImageTk.PhotoImage(load)
img = Label(schermata, image = render)
img.image = render
img.place( x = 10, y = 10 )
def testo(self):
self.testo = Text(schermata, width = 110, height = 35, border = 5, bg = "black", fg ="white")
self.testo.place( x = 400, y = 20 )
def statistiche(self):
self.stats = Text(schermata, width = 40, height = 10, border = 5, bg = "black", fg ="white")
self.stats.place( x = 10, y = (screen_height - 200))
def inserisci(self):
fraseInserita = self.inserimento.get()
scrivere(fraseInserita)
self.inserimento.delete('0', END)
def inserimenti(self):
self.inserimento = Entry(schermata,font=large_font, width = 25, border = 5, bg = "black", fg ="white")
self.inserimento.place( x = 400, y = (screen_height - 100))
self.bottone = Button(schermata, width = 30, height = 3, border = 5, text = "Inserisci", command = self.inserisci)
self.bottone.place( x = (screen_width - 300), y = (screen_height - 100))
g = GUI(schermata)
def scrivere(scrittura):
g.testo.insert('1.0', scrittura)
def cancellaTesti():
g.testo.delete('0',END)
def wait(secondi):
time.sleep(secondi)
Levels class
from GUI import *
g = GUI(schermata)
class Livelli():
def __init__(self): pass
def cicloLivelli(self):
self.presentazione()
def presentazione(self):
scrivere("Salve avventuriero, qual e' il tuo nome?")
Main
from GUI import *
a = GUI(schermata)
l = Livelli()
if __name__ == "__main__":
a.mainloop()
l.cicloLivelli()
As you see i called the function back[(scrivere)], but the interpreter won't let the string appear in the Text widget. I've just posted the class of the GUI and the class of the "levels" that i'm looking forward to use for creating, of course, my levels for the game i'm creating. I'm searching for an answer and can't find it, hope you guys can help.
The get something on the screen you need to include self.config(width=700, heigh=800) (width and height totally arbitrary :)!) before self.pack() in class GUI and change all schermata into self (as you have defined the instance of GUI as the master frame).
I made the program put something on screen with the version below and I had to define some variables like screen_height, screen_width just so to prove the concept.
I also defined the method scrivere. Anyway it is rendering something so hopefully you can proceed. Good luck.
import tkinter as tk
class GUI(tk.Frame):
def __init__(self):
super(GUI, self).__init__()
self.config(width=700, height=500)
self.pack()
# self.bg()
# self.immagine()
self.testo()
self.statistiche()
self.inserimenti()
def bg(self):
load = Image.open("immagini\\background.png")
render = ImageTk.PhotoImage(load)
img = Label(self, image = render)
img.image = render
img.pack()
def immagine(self):
load = Image.open("immagini\\dn.png")
render = ImageTk.PhotoImage(load)
img = Label(self, image = render)
img.image = render
img.place( x = 10, y = 10 )
def testo(self):
self.testo = tk.Text(self, width = 110, height = 35, border = 5, bg = "black", fg ="white")
self.testo.place( x = 400, y = 20 )
def statistiche(self):
screen_height = 400
self.stats = tk.Text(self, width = 40, height = 10, border = 5, bg = "black", fg ="white")
self.stats.place( x = 10, y = (screen_height - 200))
def inserisci(self):
fraseInserita = self.inserimento.get()
self.scrivere(fraseInserita)
self.inserimento.delete('0', 'end')
def inserimenti(self):
large_font = ('calibri', 12)
screen_height = 400
screen_width = 600
self.inserimento = tk.Entry(self,font=large_font, width = 25, border = 5, bg = "black", fg ="white")
self.inserimento.place( x = 400, y = (screen_height - 100))
self.bottone = tk.Button(self, width = 30, height = 3, border = 5, text = "Inserisci", command = self.inserisci)
self.bottone.place( x = (screen_width - 300), y = (screen_height - 100))
def scrivere(self, frase):
print(' you need to define this function when button is pressed')
class Livelli():
def __init__(self):
pass
def cicloLivelli(self):
self.presentazione()
def presentazione(self):
print("Salve avventuriero, qual e' il tuo nome?")
if __name__ == "__main__":
a = GUI()
l = Livelli()
l.cicloLivelli()
a.mainloop()
I'm creating in tkinter a Crop Tool that is similar in Photoshop. This code has a function that is supposed to crop a moveable image within the cropping box (2 in x 2 in, passport size, and so on). The problem is, the code often crops portions of the image outside the box.
For example, if I have a portrait and aimed the face at the rectangle, the code would crop the hat instead, or anywhere but the face.
I tried to use bbox, event objects, etc. but the measurements end up wrong. Please help me. Thanks.
Here is a partial code. Sorry if it's a quite lengthy.
from tkinter import *
from tkinter import ttk
import tkinter as tk
from tkinter import messagebox
from tkinter.filedialog import askopenfilename, asksaveasfilename
from PIL import Image, ImageTk
class PictureEditor:
# Quits when called
#staticmethod
# Opens an image
def open_app(self, event=None):
self.canvas.delete(ALL)
# Opens a window to choose a file=
self.openfile = askopenfilename(initialdir = # "Filename here")
if self.openfile:
with open(self.openfile) as _file:
# if file is selected by user, I'm going to delete
# the contents inside the canvas widget
self.canvas.delete(1.0, END)
self.im = Image.open(self.openfile)
self.image = ImageTk.PhotoImage(self.im)
self.a1 = self.canvas.create_image(0, 0, anchor=NW,
image=self.image, tags="image")
self.image_dim = self.canvas.bbox(self.a1)
self.imx = self.image_dim[0]
self.imy = self.image_dim[1]
# updating text widget
window.update_idletasks()
def on_drag(self, event):
# record the item and its location
self._drag_data["item"] = self.canvas.find_closest(event.x, event.y)[0]
self._drag_data["x"] = event.x
self._drag_data["y"] = event.y
self.origx = event.x
self.origy = event.y
def on_release(self, event):
# when I release the mouse, this happens
# reset the drag information
self._drag_data["item"] = None
self._drag_data["x"] = 0
self._drag_data["y"] = 0
self.newx = event.x
self.newy = event.y
# Measures mouse movement from one point to another
self.movex = self.origx - self.newx
self.movey = self.origy - self.newy
def on_motion(self, event):
# handles the dragging of an object
# compute how much the mouse has moved
delta_x = event.x - self._drag_data["x"]
delta_y = event.y - self._drag_data["y"]
# move the object the appropriate amount
self.canvas.move(self._drag_data["item"], delta_x, delta_y)
# record the new position
self._drag_data["x"] = event.x
self._drag_data["y"] = event.y
def draw(self, event, x1=None, y1=None,x2=None,y2=None):
# deleting contents of border, if any.
try:
self.canvas.delete(self.border)
except:
pass
# if an item is selected
selection = self.combo.get()
if selection == 'No Crop':
x1, y1, x2, y2 = None, None, None, None
if selection == '2 in x 2 in':
x1, y1, x2, y2 = self.imx, self.imy, self.imx + 200, self.imy + 200
if selection == '1 in x 1 in':
x1, y1, x2, y2 = self.imx, self.imy, self.imx + 100, self.imy + 100
if selection == 'Passport Size':
x1, y1, x2, y2 = self.imx, self.imy, self.imx + 132.28, self.imy
+170.079
if x1 != None or y1 != None or x2 != None or y2 != None:
self.dimensions = {"x1":x1, "y1":y1, "x2":x2, "y2":y2}
width = 5
self.border = self.canvas.create_rectangle(x1+ width, y1 +
width, x2 + width, y2 + width, width=width, outline="#ffffff", fill ="",
tags = "rectangle")
else:
pass
def crop(self, event=None):
# cropping the image
try:
self.crop_image = self.im.crop((self.dimensions["x1"] +
self.movex,
self.dimensions["y1"] + self.movey,
self.dimensions["x2"] + self.movex,
self.dimensions["y2"] + self.movey))
except:
print("cropping failed")
return 1
self.newly_cropped = ImageTk.PhotoImage(self.crop_image)
try:
new_image = self.canvas.create_image(120, 120,
image=self.newly_cropped)
print("Image is cropped")
except:
print("Cropping failed")
def __init__(self,window):
frame1 = Frame(bg='red')
frame1.pack(side=TOP, fill=X)
frame2height = 600
frame2width = 600
frame2 = Frame(window, bd=2, relief=SUNKEN)
frame2.pack(side=LEFT, fill=X)
frame3 = Frame(bg='green')
frame3.pack(side=LEFT, fill=X)
# Button that open pictures
open = Button(frame1, text='Open Pic', padx=20, command =
self.open_app)
open.pack(pady=5, padx=5, side=LEFT)
# Creating a canvas widget
self.canvas = tk.Canvas(frame2, height=frame2height,
width=frame2width,
bg='gray')
self.xsb = Scrollbar(frame2, orient="horizontal",
command=self.canvas.xview)
self.ysb = Scrollbar(frame2, orient="vertical",
command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.ysb.set,
xscrollcommand=self.xsb.set)
self.canvas.configure(scrollregion=(0, 0, 1000, 1000))
# keeps track of data being dragged
self._drag_data = {"x": 0, "y": 0, "item": None}
# creating image and crop border
self.canvas.tag_bind("image","<ButtonPress-1>", self.on_drag)
self.canvas.tag_bind("image","<ButtonRelease-1>", self.on_release)
self.canvas.tag_bind("image","<B1-Motion>", self.on_motion)
# widget positions in frame2
self.xsb.pack(side=BOTTOM, fill=X)
self.canvas.pack(side=LEFT)
self.ysb.pack(side=LEFT, fill=Y)
self.combo = ttk.Combobox(frame1)
# Combobox selections
self.combo['values'] = ('No Crop', '2 in x 2 in', '1 in x 1 in',
'Passport Size')
self.combo.current(0)
self.combo.pack(pady=5, padx=5, side=LEFT)
self.combo.bind("<Button-1>", self.draw)
# Button that crops picture
self.crop = Button(frame1, text='Crop Pic', padx=20,
command=self.crop)
self.crop.pack(pady=5, padx=5, side=LEFT)
# this window has all the properties of tkinter.
# .Tk() declares this variable as the frame
window = tk.Tk()
# .title() will input whatever title you want for the app
window.title("ID Picture Generator")
# .geometry() sets the size in pixels of what the window will be
window.geometry("800x600")
app = PictureEditor(window)
# runs everything inside the window
window.mainloop()
So after hours or reading post and looking at the documentation for tkinter I have found that on windows machines the color options for tkinter scrollbar will not work due to the scrollbar getting its theme from windows directly. My problem is the color of the default theme really clashes with my program and I am trying to find a solution that does not involve importing a different GUI package such as PyQt (I don't have access to pip at work so this is a problem to get new packages)
Aside from using a separate package can anyone point me towards some documentation on how to write my own sidebar for scrolling through the text widget. All I have found so far that is even close to what I want to be able to do is an answer on this question. (Changing the apperance of a scrollbar in tkinter using ttk styles)
From what I can see the example is only changing the background of the scrollbar and with that I was still unable to use the example. I got an error on one of the lines used to configure the style.
style.configure("My.Horizontal.TScrollbar", *style.configure("Horizontal.TScrollbar"))
TypeError: configure() argument after * must be an iterable, not NoneType
Not sure what to do with this error because I was just following the users example and I am not sure as to why it worked for them but not for me.
What I have tried so far is:
How I create my text box and the scrollbars to go with it.
root.text = Text(root, undo = True)
root.text.grid(row = 0, column = 1, columnspan = 1, rowspan = 1, padx =(5,5), pady =(5,5), sticky = W+E+N+S)
root.text.config(bg = pyFrameColor, fg = "white", font=('times', 16))
root.text.config(wrap=NONE)
vScrollBar = tkinter.Scrollbar(root, command=root.text.yview)
hScrollBar = tkinter.Scrollbar(root, orient = HORIZONTAL, command=root.text.xview)
vScrollBar.grid(row = 0, column = 2, columnspan = 1, rowspan = 1, padx =1, pady =1, sticky = E+N+S)
hScrollBar.grid(row = 1 , column = 1, columnspan = 1, rowspan = 1, padx =1, pady =1, sticky = S+W+E)
root.text['yscrollcommand'] = vScrollBar.set
root.text['xscrollcommand'] = hScrollBar.set
Following the documentation here My attempt below does not appear to do anything on windows machine. As I have read on other post this has to do with the scrollbar getting its theme natively from windows.
vScrollBar.config(bg = mainBGcolor)
vScrollBar['activebackground'] = mainBGcolor
hScrollBar.config(bg = mainBGcolor)
hScrollBar['activebackground'] = mainBGcolor
I guess it all boils down to:
Is it possible to create my own sidebar (with colors I can change per theme) without the need to import other python packages? If so, where should I start or can someone please link me to the documentation as my searches always seam to lead me back to Tkinter scrollbar Information. As these config() options do work for linux they do not work for windows.
not a complete answer, but have you considered creating your own scrollbar lookalike:
import tkinter as tk
class MyScrollbar(tk.Canvas):
def __init__(self, master, *args, **kwargs):
if 'width' not in kwargs:
kwargs['width'] = 10
if 'bd' not in kwargs:
kwargs['bd'] = 0
if 'highlightthickness' not in kwargs:
kwargs['highlightthickness'] = 0
self.command = kwargs.pop('command')
tk.Canvas.__init__(self, master, *args, **kwargs)
self.elements = { 'button-1':None,
'button-2':None,
'trough':None,
'thumb':None}
self._oldwidth = 0
self._oldheight = 0
self._sb_start = 0
self._sb_end = 1
self.bind('<Configure>', self._resize)
self.tag_bind('button-1', '<Button-1>', self._button_1)
self.tag_bind('button-2', '<Button-1>', self._button_2)
self.tag_bind('trough', '<Button-1>', self._trough)
self._track = False
self.tag_bind('thumb', '<ButtonPress-1>', self._thumb_press)
self.tag_bind('thumb', '<ButtonRelease-1>', self._thumb_release)
self.tag_bind('thumb', '<Leave>', self._thumb_release)
self.tag_bind('thumb', '<Motion>', self._thumb_track)
def _sort_kwargs(self, kwargs):
for key in kwargs:
if key in ['buttontype', 'buttoncolor', 'troughcolor', 'thumbcolor', 'thumbtype']:
self._scroll_kwargs[key] = kwargs.pop(key) # add to custom dict and remove from canvas dict
return kwargs
def _resize(self, event):
width = self.winfo_width()
height = self.winfo_height()
# print("canvas: (%s, %s)" % (width, height))
if self.elements['button-1']: # exists
if self._oldwidth != width:
self.delete(self.elements['button-1'])
self.elements['button-1'] = None
else:
pass
if not self.elements['button-1']: # create
self.elements['button-1'] = self.create_oval((0,0,width, width), fill='#006cd9', outline='#006cd9', tag='button-1')
if self.elements['button-2']: # exists
coords = self.coords(self.elements['button-2'])
if self._oldwidth != width:
self.delete(self.elements['button-2'])
self.elements['button-2'] = None
elif self._oldheight != height:
self.move(self.elements['button-2'], 0, height-coords[3])
else:
pass
if not self.elements['button-2']: # create
self.elements['button-2'] = self.create_oval((0,height-width,width, height), fill='#006cd9', outline='#006cd9', tag='button-2')
if self.elements['trough']: # exists
coords = self.coords(self.elements['trough'])
if (self._oldwidth != width) or (self._oldheight != height):
self.delete(self.elements['trough'])
self.elements['trough'] = None
else:
pass
if not self.elements['trough']: # create
self.elements['trough'] = self.create_rectangle((0,int(width/2),width, height-int(width/2)), fill='#00468c', outline='#00468c', tag='trough')
self.set(self._sb_start, self._sb_end) # hacky way to redraw thumb
self.tag_raise('thumb') # ensure thumb always on top of trough
self._oldwidth = width
self._oldheight = height
def _button_1(self, event):
self.command('scroll', -1, 'pages')
return 'break'
def _button_2(self, event):
self.command('scroll', 1, 'pages')
return 'break'
def _trough(self, event):
width = self.winfo_width()
height = self.winfo_height()
size = (self._sb_end - self._sb_start) / 1
thumbrange = height - width
thumbsize = int(thumbrange * size)
thumboffset = int(thumbrange * self._sb_start) + int(width/2)
thumbpos = int(thumbrange * size / 2) + thumboffset
if event.y < thumbpos:
self.command('scroll', -1, 'pages')
elif event.y > thumbpos:
self.command('scroll', 1, 'pages')
return 'break'
def _thumb_press(self, event):
print("thumb press: (%s, %s)" % (event.x, event.y))
self._track = True
def _thumb_release(self, event):
print("thumb release: (%s, %s)" % (event.x, event.y))
self._track = False
def _thumb_track(self, event):
if self._track:
# print("*"*30)
print("thumb: (%s, %s)" % (event.x, event.y))
width = self.winfo_width()
height = self.winfo_height()
# print("window size: (%s, %s)" % (width, height))
size = (self._sb_end - self._sb_start) / 1
# print('size: %s' % size)
thumbrange = height - width
# print('thumbrange: %s' % thumbrange)
thumbsize = int(thumbrange * size)
# print('thumbsize: %s' % thumbsize)
clickrange = thumbrange - thumbsize
# print('clickrange: %s' % clickrange)
thumboffset = int(thumbrange * self._sb_start) + int(width/2)
# print('thumboffset: %s' % thumboffset)
thumbpos = int(thumbrange * size / 2) + thumboffset
# print("mouse point: %s" % event.y)
# print("thumbpos: %s" % thumbpos)
point = (event.y - (width/2) - (thumbsize/2)) / clickrange
# point = (event.y - (width / 2)) / (thumbrange - thumbsize)
# print(event.y - (width/2))
# print(point)
if point < 0:
point = 0
elif point > 1:
point = 1
# print(point)
self.command('moveto', point)
return 'break'
def set(self, *args):
oldsize = (self._sb_end - self._sb_start) / 1
self._sb_start = float(args[0])
self._sb_end = float(args[1])
size = (self._sb_end - self._sb_start) / 1
width = self.winfo_width()
height = self.winfo_height()
if oldsize != size:
self.delete(self.elements['thumb'])
self.elements['thumb'] = None
thumbrange = height - width
thumbsize = int(thumbrange * size)
thumboffset = int(thumbrange * self._sb_start) + int(width/2)
if not self.elements['thumb']: # create
self.elements['thumb'] = self.create_rectangle((0, thumboffset,width, thumbsize+thumboffset), fill='#4ca6ff', outline='#4ca6ff', tag='thumb')
else: # move
coords = self.coords(self.elements['thumb'])
if (thumboffset != coords[1]):
self.move(self.elements['thumb'], 0, thumboffset-coords[1])
return 'break'
if __name__ == '__main__':
root = tk.Tk()
lb = tk.Listbox(root)
lb.pack(side='left', fill='both', expand=True)
for num in range(0,100):
lb.insert('end', str(num))
sb = MyScrollbar(root, width=50, command=lb.yview)
sb.pack(side='right', fill='both', expand=True)
lb.configure(yscrollcommand=sb.set)
root.mainloop()
I've left my comments in, and for the life of me i can't seem to get click and dragging the thumb to work correctly, but its a simple scrollbar with the following features:
up and down buttons that can be coloured
thumb and trough that can be individually coloured
tracks movement in scrollable widget
thumb resizes with size of scroll area
Edit
I've revised the thumb code to fix the click and drag scrolling:
import tkinter as tk
class MyScrollbar(tk.Canvas):
def __init__(self, master, *args, **kwargs):
self._scroll_kwargs = { 'command':None,
'orient':'vertical',
'buttontype':'round',
'buttoncolor':'#006cd9',
'troughcolor':'#00468c',
'thumbtype':'rectangle',
'thumbcolor':'#4ca6ff',
}
kwargs = self._sort_kwargs(kwargs)
if self._scroll_kwargs['orient'] == 'vertical':
if 'width' not in kwargs:
kwargs['width'] = 10
elif self._scroll_kwargs['orient'] == 'horizontal':
if 'height' not in kwargs:
kwargs['height'] = 10
else:
raise ValueError
if 'bd' not in kwargs:
kwargs['bd'] = 0
if 'highlightthickness' not in kwargs:
kwargs['highlightthickness'] = 0
tk.Canvas.__init__(self, master, *args, **kwargs)
self.elements = { 'button-1':None,
'button-2':None,
'trough':None,
'thumb':None}
self._oldwidth = 0
self._oldheight = 0
self._sb_start = 0
self._sb_end = 1
self.bind('<Configure>', self._resize)
self.tag_bind('button-1', '<Button-1>', self._button_1)
self.tag_bind('button-2', '<Button-1>', self._button_2)
self.tag_bind('trough', '<Button-1>', self._trough)
self._track = False
self.tag_bind('thumb', '<ButtonPress-1>', self._thumb_press)
self.bind('<ButtonRelease-1>', self._thumb_release)
# self.bind('<Leave>', self._thumb_release)
self.bind('<Motion>', self._thumb_track)
def _sort_kwargs(self, kwargs):
to_remove = []
for key in kwargs:
if key in [ 'buttontype', 'buttoncolor', 'buttonoutline',
'troughcolor', 'troughoutline',
'thumbcolor', 'thumbtype', 'thumboutline',
'command', 'orient']:
self._scroll_kwargs[key] = kwargs[key] # add to custom dict
to_remove.append(key)
for key in to_remove:
del kwargs[key]
return kwargs
def _get_colour(self, element):
if element in self._scroll_kwargs: # if element exists in settings
return self._scroll_kwargs[element]
if element.endswith('outline'): # if element is outline and wasn't in settings
return self._scroll_kwargs[element.replace('outline', 'color')] # fetch default for main element
def _width(self):
return self.winfo_width() - 2 # return width minus 2 pixes to ensure fit in canvas
def _height(self):
return self.winfo_height() - 2 # return height minus 2 pixes to ensure fit in canvas
def _resize(self, event):
width = self._width()
height = self._height()
if self.elements['button-1']: # exists
# delete element if vertical scrollbar and width changed
# or if horizontal and height changed, signals button needs to change
if (((self._oldwidth != width) and (self._scroll_kwargs['orient'] == 'vertical')) or
((self._oldheight != height) and (self._scroll_kwargs['orient'] == 'horizontal'))):
self.delete(self.elements['button-1'])
self.elements['button-1'] = None
if not self.elements['button-1']: # create
size = width if (self._scroll_kwargs['orient'] == 'vertical') else height
rect = (0,0,size, size)
fill = self._get_colour('buttoncolor')
outline = self._get_colour('buttonoutline')
if (self._scroll_kwargs['buttontype'] == 'round'):
self.elements['button-1'] = self.create_oval(rect, fill=fill, outline=outline, tag='button-1')
elif (self._scroll_kwargs['buttontype'] == 'square'):
self.elements['button-1'] = self.create_rectangle(rect, fill=fill, outline=outline, tag='button-1')
if self.elements['button-2']: # exists
coords = self.coords(self.elements['button-2'])
# delete element if vertical scrollbar and width changed
# or if horizontal and height changed, signals button needs to change
if (((self._oldwidth != width) and (self._scroll_kwargs['orient'] == 'vertical')) or
((self._oldheight != height) and (self._scroll_kwargs['orient'] == 'horizontal'))):
self.delete(self.elements['button-2'])
self.elements['button-2'] = None
# if vertical scrollbar and height changed button needs to move
elif ((self._oldheight != height) and (self._scroll_kwargs['orient'] == 'vertical')):
self.move(self.elements['button-2'], 0, height-coords[3])
# if horizontal scrollbar and width changed button needs to move
elif ((self._oldwidth != width) and (self._scroll_kwargs['orient'] == 'horizontal')):
self.move(self.elements['button-2'], width-coords[2], 0)
if not self.elements['button-2']: # create
if (self._scroll_kwargs['orient'] == 'vertical'):
rect = (0,height-width,width, height)
elif (self._scroll_kwargs['orient'] == 'horizontal'):
rect = (width-height,0,width, height)
fill = self._get_colour('buttoncolor')
outline = self._get_colour('buttonoutline')
if (self._scroll_kwargs['buttontype'] == 'round'):
self.elements['button-2'] = self.create_oval(rect, fill=fill, outline=outline, tag='button-2')
elif (self._scroll_kwargs['buttontype'] == 'square'):
self.elements['button-2'] = self.create_rectangle(rect, fill=fill, outline=outline, tag='button-2')
if self.elements['trough']: # exists
coords = self.coords(self.elements['trough'])
# delete element whenever width or height changes
if (self._oldwidth != width) or (self._oldheight != height):
self.delete(self.elements['trough'])
self.elements['trough'] = None
if not self.elements['trough']: # create
if (self._scroll_kwargs['orient'] == 'vertical'):
rect = (0, int(width/2), width, height-int(width/2))
elif (self._scroll_kwargs['orient'] == 'horizontal'):
rect = (int(height/2), 0, width-int(height/2), height)
fill = self._get_colour('troughcolor')
outline = self._get_colour('troughoutline')
self.elements['trough'] = self.create_rectangle(rect, fill=fill, outline=outline, tag='trough')
self.set(self._sb_start, self._sb_end) # hacky way to redraw thumb without moving it
self.tag_raise('thumb') # ensure thumb always on top of trough
self._oldwidth = width
self._oldheight = height
def _button_1(self, event):
command = self._scroll_kwargs['command']
if command:
command('scroll', -1, 'pages')
return 'break'
def _button_2(self, event):
command = self._scroll_kwargs['command']
if command:
command('scroll', 1, 'pages')
return 'break'
def _trough(self, event):
# print('trough: (%s, %s)' % (event.x, event.y))
width = self._width()
height = self._height()
coords = self.coords(self.elements['trough'])
if (self._scroll_kwargs['orient'] == 'vertical'):
trough_size = coords[3] - coords[1]
elif (self._scroll_kwargs['orient'] == 'horizontal'):
trough_size = coords[2] - coords[0]
# print('trough size: %s' % trough_size)
size = (self._sb_end - self._sb_start) / 1
if (self._scroll_kwargs['orient'] == 'vertical'):
thumbrange = height - width
elif (self._scroll_kwargs['orient'] == 'horizontal'):
thumbrange = width - height
thumbsize = int(thumbrange * size)
if (self._scroll_kwargs['orient'] == 'vertical'):
thumboffset = int(thumbrange * self._sb_start) + int(width/2)
elif (self._scroll_kwargs['orient'] == 'horizontal'):
thumboffset = int(thumbrange * self._sb_start) + int(height/2)
thumbpos = int(thumbrange * size / 2) + thumboffset
command = self._scroll_kwargs['command']
if command:
if (((self._scroll_kwargs['orient'] == 'vertical') and (event.y < thumbpos)) or
((self._scroll_kwargs['orient'] == 'horizontal') and (event.x < thumbpos))):
command('scroll', -1, 'pages')
elif (((self._scroll_kwargs['orient'] == 'vertical') and (event.y > thumbpos)) or
((self._scroll_kwargs['orient'] == 'horizontal') and (event.x > thumbpos))):
command('scroll', 1, 'pages')
return 'break'
def _thumb_press(self, event):
self._track = True
def _thumb_release(self, event):
self._track = False
def _thumb_track(self, event):
# print('track')
if self._track:
width = self._width()
height = self._height()
# print("window size: (%s, %s)" % (width, height))
size = (self._sb_end - self._sb_start) / 1
coords = self.coords(self.elements['trough'])
# print('trough coords: %s' % coords)
if (self._scroll_kwargs['orient'] == 'vertical'):
trough_size = coords[3] - coords[1]
thumbrange = height - width
elif (self._scroll_kwargs['orient'] == 'horizontal'):
trough_size = coords[2] - coords[0]
thumbrange = width - height
# print('trough size: %s' % trough_size)
thumbsize = int(thumbrange * size)
if (self._scroll_kwargs['orient'] == 'vertical'):
pos = max(min(trough_size, event.y - coords[1] - (thumbsize/2)), 0)
elif (self._scroll_kwargs['orient'] == 'horizontal'):
pos = max(min(trough_size, event.x - coords[0] - (thumbsize/2)), 0)
# print('pos: %s' % pos)
point = pos / trough_size
# print('point: %s' % point)
command = self._scroll_kwargs['command']
if command:
command('moveto', point)
return 'break'
def set(self, *args):
# print('set: %s' % str(args))
oldsize = (self._sb_end - self._sb_start) / 1
self._sb_start = float(args[0])
self._sb_end = float(args[1])
size = (self._sb_end - self._sb_start) / 1
width = self._width()
height = self._height()
if oldsize != size:
self.delete(self.elements['thumb'])
self.elements['thumb'] = None
if (self._scroll_kwargs['orient'] == 'vertical'):
thumbrange = height - width
thumboffset = int(thumbrange * self._sb_start) + int(width/2)
elif (self._scroll_kwargs['orient'] == 'horizontal'):
thumbrange = width - height
thumboffset = int(thumbrange * self._sb_start) + int(height/2)
thumbsize = int(thumbrange * size)
if not self.elements['thumb']: # create
if (self._scroll_kwargs['orient'] == 'vertical'):
rect = (0, thumboffset,width, thumbsize+thumboffset)
elif (self._scroll_kwargs['orient'] == 'horizontal'):
rect = (thumboffset, 0, thumbsize+thumboffset, height)
fill = self._get_colour('thumbcolor')
outline = self._get_colour('thumboutline')
if (self._scroll_kwargs['thumbtype'] == 'round'):
self.elements['thumb'] = self.create_oval(rect, fill=fill, outline=outline, tag='thumb')
elif (self._scroll_kwargs['thumbtype'] == 'rectangle'):
self.elements['thumb'] = self.create_rectangle(rect, fill=fill, outline=outline, tag='thumb')
else: # move
coords = self.coords(self.elements['thumb'])
if (self._scroll_kwargs['orient'] == 'vertical'):
if (thumboffset != coords[1]):
self.move(self.elements['thumb'], 0, thumboffset-coords[1])
elif (self._scroll_kwargs['orient'] == 'horizontal'):
if (thumboffset != coords[1]):
self.move(self.elements['thumb'], thumboffset-coords[0], 0)
return 'break'
if __name__ == '__main__':
root = tk.Tk()
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(1, weight=1)
root.grid_rowconfigure(3, weight=1)
root.grid_columnconfigure(3, weight=1)
lb = tk.Listbox(root)
lb.grid(column=1, row=1, sticky="nesw")
for num in range(0,100):
lb.insert('end', str(num)*100)
sby1 = MyScrollbar(root, width=50, command=lb.yview)
sby1.grid(column=2, row=1, sticky="nesw")
sby2 = MyScrollbar(root, width=50, command=lb.yview, buttontype='square', thumbtype='round')
sby2.grid(column=4, row=1, sticky="nesw")
sbx1 = MyScrollbar(root, height=50, command=lb.xview, orient='horizontal', buttoncolor='red', thumbcolor='orange', troughcolor='green')
sbx1.grid(column=1, row=2, sticky="nesw")
sbx2 = MyScrollbar(root, height=50, command=lb.xview, orient='horizontal', thumbtype='round')
sbx2.grid(column=1, row=4, sticky="nesw")
def x_set(*args):
sbx1.set(*args)
sbx2.set(*args)
def y_set(*args):
sby1.set(*args)
sby2.set(*args)
lb.configure(yscrollcommand=y_set, xscrollcommand=x_set)
root.mainloop()
so I've fixed the calculation to work out where the new scroll to position will be, and changed from binding on the thumb tag for the track and release events to binding on the whole canvas, so if the user scrolls quickly the binding will still release when the mouse is let go.
I've commented out the binding for when the cursor leaves the canvas so the behavior more closely mimics the existing scroll bar, but can be re enabled if you want it to stop scrolling if the mouse leaves the widget.
As for making two classes, the amended code above lets you use the orient keyword so you can just drop this class (with styling changes) in place of the default scrollbar, as shown in the example at the bottom.