Scrollable frame does not fill canvas - python

I use Python 2.7 and I have a scrollable frame where the canvas is not shrinking to fit the frame I want to make scrollable.
I looked at this question for an answer but it does not work when I run it:
How to resize a scrollable frame to fill the canvas?
When I print the width of the frame inside the canvas, it says 0.
I also ran the code from the answer of this question on my computer :
Scrollable Frame does not resize properly using tkinter in Python
but it will still show the white canvas to the left of the labels, and it does not resize when the labels are deleted.
It looks like this:
This is my code, based on the answer in this question:
Adding a scrollbar to a group of widgets in Tkinter
from Tkinter import *
class Scrollable_frame(Frame):
def __init__(self, parent, title, values):
self.parent = parent
Frame.__init__(self, self.parent)
self.canvas = Canvas(self, borderwidth=0, background="#ffffff")
self.scrollbar = Scrollbar(self, command=self.canvas.yview)
self.innerFrame = Radiobutton_frame(self.canvas,title,values)
self.canvas.configure(yscrollcommand=self.scrollbar.set)
self.canvas.grid(row=0, column=0, sticky= N+S)
self.scrollbar.grid(row=0, column=1, sticky = N+S)
self.canvas.create_window((0,0),window = self.innerFrame,anchor="nw")
self.innerFrame.bind("<Configure>", self.set_canvas_scrollregion)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
def set_canvas_scrollregion(self, event):
width = event.width - 4
self.canvas.itemconfigure("self.innerFrame ", width=width)
self.canvas.config(scrollregion=self.canvas.bbox("all"))
class Radiobutton_frame(LabelFrame):
def __init__(self, parent, title, values):
"""
In: parent - Canvas
title - String
values - List of Int
"""
self.radiobuttons = {}
self.parent = parent
self.selection = StringVar()
self.selection.set("init")
LabelFrame.__init__(self, self.parent, text = title)
for value in values:
self.add_radiobutton(value)
def add_radiobutton(self, value):
"""
Adds a radiobutton to the frame.
In: item - String
"""
# Associate to same variable to make them function as a group
self.radiobuttons[value] = Radiobutton(master = self,
variable = self.selection,
text = value,
value = value)
self.radiobuttons[value].pack(anchor=W)
# Usage example
root = Tk()
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
scrollableFrame = Scrollable_frame(root, "Canvas not resizing", range(30))
scrollableFrame.grid(row=0, column=0, sticky=N+S+E+W)
if __name__ == '__main__':
root.mainloop()

I don't think above question's code snippet fits to a Minimal, Complete, and Verifiable example but at the very least it's runnable.
You have three mistakes compared to that of: How to resize a scrollable frame to fill the canvas?
The most significant of which is that in the linked question, the OP uses the option tags where you don't. Replace:
self.canvas.create_window((0,0),window = self.innerFrame,anchor="nw")
with:
self.canvas.create_window((0,0),window = self.innerFrame, anchor="nw", tags="my_tag")
Another mistake is that you're binding the event of a frame's resizing as opposed to the actual Canvas' resizing, also pointed out in Bryan's comment here. Replace:
self.innerFrame.bind("<Configure>", self.set_canvas_scrollregion)
with:
self.canvas.bind("<Configure>", self.set_canvas_scrollregion)
Lastly, tkinter doesn't seem to accept space character with tags, replace:
self.canvas.itemconfigure("self.innerFrame ", width=width)
with:
self.canvas.itemconfigure("my_tag", width=width)
Finally, you should have:
from Tkinter import *
class Scrollable_frame(Frame):
def __init__(self, parent, title, values):
self.parent = parent
Frame.__init__(self, self.parent)
self.canvas = Canvas(self, borderwidth=0, background="#ffffff")
self.scrollbar = Scrollbar(self, command=self.canvas.yview)
self.innerFrame = Radiobutton_frame(self.canvas,title,values)
self.canvas.configure(yscrollcommand=self.scrollbar.set)
self.canvas.grid(row=0, column=0, sticky= N+S)
self.scrollbar.grid(row=0, column=1, sticky = N+S)
self.canvas.create_window((0,0),window = self.innerFrame,anchor="nw",
tags="my_tag")
self.canvas.bind("<Configure>", self.set_canvas_scrollregion)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
def set_canvas_scrollregion(self, event):
width = event.width - 4
self.canvas.itemconfigure("my_tag", width=width)
self.canvas.config(scrollregion=self.canvas.bbox("all"))
class Radiobutton_frame(LabelFrame):
def __init__(self, parent, title, values):
"""
In: parent - Canvas
title - String
values - List of Int
"""
self.radiobuttons = {}
self.parent = parent
self.selection = StringVar()
self.selection.set("init")
LabelFrame.__init__(self, self.parent, text = title)
for value in values:
self.add_radiobutton(value)
def add_radiobutton(self, value):
"""
Adds a radiobutton to the frame.
In: item - String
"""
# Associate to same variable to make them function as a group
self.radiobuttons[value] = Radiobutton(master = self,
variable = self.selection,
text = value,
value = value)
self.radiobuttons[value].pack(anchor=W)
# Usage example
root = Tk()
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
scrollableFrame = Scrollable_frame(root, "Canvas not resizing", range(30))
scrollableFrame.grid(row=0, column=0, sticky=N+S+E+W)
if __name__ == '__main__':
root.mainloop()

Related

How can i put my taskbar to be always on top?

I want to place my menubar frame to the top of the window like the tkinter's Menu module.
class My_Menu:
def __init__(self, master, name="Default", expand="full", mode="bar"):
##### create the frame #####
self.menus = {}
self.master = master
self.master.columnconfigure(0, weight=1)
self.master.rowconfigure(0, weight=0)
self.master_frame = Frame(self.master)
self.master_frame.grid(row=0, column=0, sticky=NSEW)
self.master_frame.columnconfigure(0, weight=1)
self.master_frame.rowconfigure(0, weight=1)
self.main_frame = Frame(self.master_frame)
self.main_frame.grid(row=0, column=0, sticky=NSEW)
self.main_frame.rowconfigure(0, weight=0)
I am not sure if there is any way to do this, but a way around will be to create space to the row and use sticky to put the menu on top always.
from tkinter import *
class MenuFrame(Frame):
def __init__(self,parent,*args,**kwargs):
Frame.__init__(self,parent,*args,**kwargs)
self.b1 = Button(self,text='File',width=50)
self.b1.grid(row=0,column=0)
self.b2 = Button(self,text='Help',width=50)
self.b2.grid(row=0,column=1)
def ret_max(self):
self.update()
return self.b1.winfo_height()
root = Tk()
menu = MenuFrame(root)
menu.grid(row=0,column=0,sticky='n') # Can move this line in or out of class
height = menu.ret_max()
root.grid_rowconfigure(0,pad=height) # Make it have extra space of height of button
Button(root,text='Dummy Button').grid(row=0,column=0,sticky='s')
root.mainloop()

tkinter frame inside of canvas not expanding to fill area

I have a scrollable frame class that I borrowed from some code I found, and I'm having trouble adjusting it to fit my needs. It was managed by .pack(), but I needed to use .grid(), so I simply packed a frame (self.region) into it so I could grid my widgets inside of that. However, the widgets inside of this frame won't expand to meet the edges of the container and I'm not sure why. Theres a lot of issues similar to mine out there, but none of the solutions seemed to help. I tried using .grid_columnconfigure, .columnconfigure(), and .bind("Configure") all to no avail. Does anyone have any suggestions to get the widgets in my scrollable region to expand east and west to fill the window?
import tkinter as tk
from tkinter import ttk
class ScrollableFrame(ttk.Frame):
"""taken from https://blog.tecladocode.com/tkinter-scrollable-frames/ and modified to
allow for the use of grid inside self.region
Class that allows for the creation of a frame that is scrollable"""
def __init__(self, container, *args, **kwargs):
super().__init__(container, *args, **kwargs)
canvas = tk.Canvas(self)
scrollbar = ttk.Scrollbar(self, orient="vertical", command=canvas.yview)
self.scrollable_frame = ttk.Frame(canvas)
canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
canvas.pack(side="left", fill="both", expand=True)
canvas.rowconfigure(0, weight=1)
canvas.columnconfigure(0, weight=1)
scrollbar.pack(side="right", fill="y")
self.scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")
)
)
self.scrollable_frame.rowconfigure(0, weight=1)
self.scrollable_frame.columnconfigure(0, weight=1)
self.region=ttk.Frame(self.scrollable_frame)
self.region.pack(fill='both', expand=1)
self.region.grid_rowconfigure(0, weight=1)
self.region.grid_columnconfigure(0, weight=1)
class OtherWindow():
"""data collector object and window"""
def __init__(self, window):
self.window=tk.Toplevel(window)
self.window.grid_columnconfigure(0, weight=1)
self.window.grid_columnconfigure(1, weight=1)
self.window.grid_columnconfigure(2, weight=1)
self.window.grid_columnconfigure(3, weight=1)
self.window.grid_rowconfigure(3, weight=1)
self.lbl1=ttk.Label(self.window, text="this is a sort of long label")
self.lbl1.grid(row=0, column=0, columnspan=2)
self.lbl2=ttk.Label(self.window, text="this is another label")
self.lbl2.grid(row=0, column=2)
self.lbl3=ttk.Label(self.window, text="Other information: blah blah blah blah")
self.lbl3.grid(row=0, column=3)
self.directions=ttk.Label(self.window, text='These are instructions that are kind of long and take'+\
'up about this much space if I had to guess so random text random text random text', wraplength=700)
self.directions.grid(row=1, column=0, columnspan=4)
self.scrolly=ScrollableFrame(self.window)
self.scrolly.grid(row=2, column=0, columnspan=4,sticky='nsew')
self.frame=self.scrolly.region
self.fillScrollRegion()
self.continueBtn=ttk.Button(self.window, text="Do Something", command=self.do)
self.continueBtn.grid(row=3, column=0, columnspan=4, sticky='nsew')
def fillScrollRegion(self):
"""fills scrollable region with label widgets"""
for i in range(15):
for j in range(5):
lbl=ttk.Label(self.frame, text="Sample text"+str(i)+' '+str(j))
lbl.grid(row=i, column=j, sticky='nsew')
def do(self):
pass
root=tk.Tk()
app=OtherWindow(root)
root.mainloop()
The problem is that the scrollframe container Frame is not filling the Canvas horizontally. Instead of bothering to fix some copy/paste, example scrollframe, and explain it, I'll just give you my scrollframe. It is substantially more robust than the one you are using, and the problem you are having doesn't exist with it. I've already plugged it into a version of your script below.
The solution to your scrollframe's issue is found in my on_canvas_configure method. It simply tells the container frame to be the same width as the canvas, on canvas <Configure> events.
import tkinter as tk, tkinter.ttk as ttk
from typing import Iterable
class ScrollFrame(tk.Frame):
def __init__(self, master, scrollspeed=5, r=0, c=0, rspan=1, cspan=1, grid={}, **kwargs):
tk.Frame.__init__(self, master, **{'width':400, 'height':300, **kwargs})
#__GRID
self.grid(**{'row':r, 'column':c, 'rowspan':rspan, 'columnspan':cspan, 'sticky':'nswe', **grid})
#allow user to set width and/or height
if {'width', 'height'} & {*kwargs}:
self.grid_propagate(0)
#give this widget weight on the master grid
self.master.grid_rowconfigure(r, weight=1)
self.master.grid_columnconfigure(c, weight=1)
#give self.frame weight on this grid
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
#_WIDGETS
self.canvas = tk.Canvas(self, bd=0, bg=self['bg'], highlightthickness=0, yscrollincrement=scrollspeed)
self.canvas.grid(row=0, column=0, sticky='nswe')
self.frame = tk.Frame(self.canvas, **kwargs)
self.frame_id = self.canvas.create_window((0, 0), window=self.frame, anchor="nw")
vsb = tk.Scrollbar(self, orient="vertical")
vsb.grid(row=0, column=1, sticky='ns')
vsb.configure(command=self.canvas.yview)
#attach scrollbar to canvas
self.canvas.configure(yscrollcommand=vsb.set)
#_BINDS
#canvas resize
self.canvas.bind("<Configure>", self.on_canvas_configure)
#frame resize
self.frame.bind("<Configure>", self.on_frame_configure)
#scroll wheel
self.canvas.bind_all('<MouseWheel>', self.on_mousewheel)
#makes frame width match canvas width
def on_canvas_configure(self, event):
self.canvas.itemconfig(self.frame_id, width=event.width)
#when frame dimensions change pass the area to the canvas scroll region
def on_frame_configure(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
#add scrollwheel feature
def on_mousewheel(self, event):
self.canvas.yview_scroll(int(-event.delta / abs(event.delta)), 'units')
#configure self.frame row(s)
def rowcfg(self, index, **options):
index = index if isinstance(index, Iterable) else [index]
for i in index:
self.frame.grid_rowconfigure(i, **options)
#so this can be used inline
return self
#configure self.frame column(s)
def colcfg(self, index, **options):
index = index if isinstance(index, Iterable) else [index]
for i in index:
self.frame.grid_columnconfigure(i, **options)
#so this can be used inline
return self
class AuxiliaryWindow(tk.Toplevel):
def __init__(self, master, **kwargs):
tk.Toplevel.__init__(self, master, **kwargs)
self.geometry('600x300+600+200')
self.attributes('-topmost', True)
self.title('This Is Another Title') #:D
#if you reconsider things, you can accomplish more with less
labels = ["this is a sort of long label",
"this is another label",
"Other information: blah blah blah blah"]
for i, text in enumerate(labels):
ttk.Label(self, text=text).grid(row=0, column=i)
self.grid_columnconfigure(i, weight=1)
#doing it this way the text will always fit the display as long as you give it enough height to work with
instr = tk.Text(self, height=3, wrap='word', bg='gray94', font='Arial 8 bold', bd=0, relief='flat')
instr.insert('1.0', ' '.join(['instructions']*20))
instr.grid(row=1, columnspan=3, sticky='nswe')
#instantiate the scrollframe, configure the first 5 columns and return the frame. it's inline mania! :p
self.scrollframe = ScrollFrame(self, 10, 2, 0, cspan=3).colcfg(range(5), weight=1).frame
self.fillScrollRegion()
#why store a reference to this? Do you intend to change/delete it later?
ttk.Button(self, text="Do Something", command=self.do).grid(row=3, columnspan=3, sticky='ew')
def fillScrollRegion(self):
"""fills scrollable region with label widgets"""
r, c = 30, 5 #math is our friend
for i in range(r*c):
ttk.Label(self.scrollframe, text=f"row_{i%r} col_{i//r}").grid(row=i%r, column=i//r, sticky='nsew')
def do(self):
pass
class Root(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.geometry('+550+150')
self.title('This Is A Title Probably Or Something') #:D
aux = AuxiliaryWindow(self)
self.mainloop()
Root() if __name__ == "__main__" else None

How to create an automatically filled scrolling grid of frames (tkinter)?

I try to create a scrolling grid of frames. I will have a variable number of frames, so I want to specify the number of columns, but not the number of rows, though we can scroll down if it is too long.
I have written some code, but now I don't know how to specify that when creating a frame (a button + 2 scales) with sounds_buttons(), it belongs to a certain row and a certain column. Also, I won't always have a multiple of 5 for the number of frames, so the last row can be constituted of only 1,2,3 or 4 frames.
The goal would be to have something like that, but with an undetermined number of rows: tkinter Canvas Scrollbar with Grid?.
Thank you very much !
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# -------------------------------- Importation ------------------------------- #
import tkinter as tk
from tkinter import messagebox
# ------------------------------ Initialisation ------------------------------ #
root = tk.Tk()
width_screen, height_screen = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (width_screen, height_screen))
# ----------------------- Creation of a list of sounds ----------------------- #
wav_files = ["a.wav","b.wav","c.wav","d.wav","e.wav","f.wav","g.wav","h.wav","i.wav","j.wav","k.wav","l.wav","m.wav","n.wav","o.wav","p.wav","q.wav","r.wav","s.wav","t.wav","u.wav","v.wav","w.wav","x.wav","y.wav","z.wav","aa.wav","bb.wav","cc.wav","dd.wav","ee.wav","ff.wav"]
# -------------------------- Vertical scrolled frame ------------------------- #
class VerticalScrolledFrame(tk.Frame):
def __init__(self, parent, *args, **kw):
tk.Frame.__init__(self, parent, *args, **kw)
# Create a frame for the canvas with non-zero row&column weights
self.frame_canvas = tk.Frame(self)
self.frame_canvas.grid(row=2, column=0, pady=(8, 0), sticky='nw')
self.frame_canvas.grid_rowconfigure(0, weight=1)
self.frame_canvas.grid_columnconfigure(0, weight=1)
# Set grid_propagate to False to allow buttons resizing later
self.frame_canvas.grid_propagate(False)
# create a canvas object and a vertical scrollbar for scrolling it
vscrollbar = tk.Scrollbar(self.frame_canvas, orient=tk.VERTICAL)
vscrollbar.grid(row=0, column=1, sticky='ns')
self.canvas = tk.Canvas(self.frame_canvas, bd=0, highlightthickness=0,
yscrollcommand=vscrollbar.set, width=root.winfo_screenwidth(), height=root.winfo_screenheight())
self.canvas.grid(row=0, column=0, sticky="news")
vscrollbar.config(command=self.canvas.yview)
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
# 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 = tk.Frame(self.canvas)
interior_id = self.canvas.create_window(0, 0, window=interior,
anchor=tk.NW)
self.interior.update_idletasks()
# 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())
self.canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != self.canvas.winfo_width():
# update the canvas's width to fit the inner frame
self.canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != self.canvas.winfo_width():
# update the inner frame's width to fill the canvas
self.canvas.itemconfigure(interior_id, width=self.canvas.winfo_width())
self.canvas.bind('<Configure>', _configure_canvas)
def _on_mousewheel(self, event):
self.canvas.yview_scroll(int(-1*(event.delta/120)), "units")
# ------------------------------- Sound buttons ------------------------------ #
class Make_sound:
def __init__(self, name, parent):
self.varbutton = tk.StringVar()
self.name = name
self.parent = parent
self.soundbuttoncreator()
def launchsound(self):
print(self.varbutton.get())
if self.varbutton.get() == 1:
self.list=[]
else:
self.list.append("A")
def soundbuttoncreator(self):
self.frame = tk.Frame(self.parent) # create a frame to hold the widgets
# use self.frame as parent instead of self.parent
self.volumescale = tk.Scale(self.frame, orient='vertical', from_=100, to=0, resolution=0.5, label='Volume',command=self.setvolume, cursor="fleur")
self.volumescale.grid(row=0,column=1, rowspan=2, sticky="nsew")
self.volumescale.set(100)
self.faderscale = tk.Scale(self.frame, orient='horizontal', from_=-1, to=1, resolution=0.01, label='Balance G/D', command=self.setbalance, cursor="fleur")
self.faderscale.grid(row=1,column=0, sticky="nsew")
self.button = tk.Checkbutton(self.frame, text=self.name, indicatoron=False, selectcolor="green", background="red", variable=self.varbutton, command=self.launchsound, cursor="plus")
self.button.grid(row=0, column=0, sticky="nsew")
self.frame.pack() # use pack() on the frame so new instance of `Make_sound` will not overlap the old instances
def setvolume(self,event):
pass
def setbalance(self,event):
pass
def sounds_buttons(parent):
for i in range(len(wav_files)):
new_name = wav_files[i][:-4]
globals()["wav_files"][i] = Make_sound(new_name,parent)
# ---------------------------------------------------------------------------- #
# Creation #
# ---------------------------------------------------------------------------- #
# ----------------------------- Buttons of sound ----------------------------- #
scframe = VerticalScrolledFrame(root)
scframe.pack(side=tk.LEFT)
sounds_buttons(scframe.interior)
root.mainloop()
EDIT 1:
I have modified the Make_sound class and sounds_buttons function. There is an error.
class Make_sound:
def __init__(self, name, parent, i):
self.varbutton = tk.StringVar()
self.name = name
self.parent = parent
self.num = i
self.soundbuttoncreator()
def launchsound(self):
print(self.varbutton.get())
if self.varbutton.get() == 1:
self.list=[]
else:
self.list.append("A")
def soundbuttoncreator(self):
self.rows = self.num//5
self.columns = self.num%5
self.frame = tk.Frame(self.parent) # create a frame to hold the widgets
# use self.frame as parent instead of self.parent
self.volumescale = tk.Scale(self.frame, orient='vertical', from_=100, to=0, resolution=0.5, label='Volume',command=self.setvolume, cursor="fleur")
self.volumescale.grid(row=0,column=1, rowspan=2, sticky="nsew")
self.volumescale.set(100)
self.faderscale = tk.Scale(self.frame, orient='horizontal', from_=-1, to=1, resolution=0.01, label='Balance G/D', command=self.setbalance, cursor="fleur")
self.faderscale.grid(row=1,column=0, sticky="nsew")
self.button = tk.Checkbutton(self.frame, text=self.name, indicatoron=False, selectcolor="green", background="red", variable=self.varbutton, command=self.launchsound, cursor="plus")
self.button.grid(row=0, column=0, sticky="nsew")
self.frame.grid(row=self.rows, column=self.columns)
def setvolume(self,event):
pass
def setbalance(self,event):
pass
def sounds_buttons(parent):
for i in range(len(wav_files)):
new_name = wav_files[i][:-4]
globals()["wav_files"][i] = Make_sound(new_name,parent,i)

How to move popup window when scrolling a tkinter treeview?

I have a tkinter treeview with a vertical scrollbar. To make it (look like) editable, I create a popup Entry when the user double-clicks on a cell of the treeview. However, I can't make the popup to move when the treeview is scrolled.
import tkinter as tk
from tkinter import ttk
class EntryPopup(ttk.Entry):
def __init__(self, parent, itemId, col, **kw):
super().__init__(parent, **kw)
self.tv = parent
self.iId = itemId
self.column = col
self['exportselection'] = False
self.focus_force()
self.bind("<Return>", self.onReturn)
def saveEdit(self):
self.tv.set(self.iId, column=self.column, value=self.get())
print("EntryPopup::saveEdit---{}".format(self.iId))
def onReturn(self, event):
self.tv.focus_set()
self.saveEdit()
self.destroy()
class EditableDataTable(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.tree = None
self.entryPopup = None
columns = ("Col1", "Col2")
# Create a treeview with vertical scrollbar.
self.tree = ttk.Treeview(self, columns=columns, show="headings")
self.tree.grid(column=0, row=0, sticky='news')
self.tree.heading("#1", text="col1")
self.tree.heading("#2", text="col2")
self.vsb = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=self.vsb.set)
self.vsb.grid(column=1, row=0, sticky='ns')
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
self.entryPopup = None
self.curSelectedRowId = ""
col1 = []
col2 = []
for r in range(50):
col1.append("data 1-{}".format(r))
col2.append("data 2-{}".format(r))
for i in range(min(len(col1),len(col2))):
self.tree.insert('', i, values=(col1[i], col2[i]))
self.tree.bind('<Double-1>', self.onDoubleClick)
def createPopup(self, row, column):
x,y,width,height = self.tree.bbox(row, column)
# y-axis offset
pady = height // 2
self.entryPopup = EntryPopup(self.tree, row, column)
self.entryPopup.place(x=x, y=y+pady, anchor='w', width=width)
def onDoubleClick(self, event):
rowid = self.tree.identify_row(event.y)
column = self.tree.identify_column(event.x)
self.createPopup(rowid, column)
root = tk.Tk()
for row in range(2):
root.grid_rowconfigure(row, weight=1)
root.grid_columnconfigure(0, weight=1)
label = tk.Label(root, text="Double-click to edit and press 'Enter'")
label.grid(row=0, column=0, sticky='news', padx=10, pady=5)
dataTable = EditableDataTable(root)
dataTable.grid(row=1, column=0, sticky="news", pady=10, padx=10)
root.geometry("450x300")
root.mainloop()
To reproduce the problem, double-click on the treeview. While the edit box is open, move your mouse pointer to hover over the treeview. Now scroll using the mouse wheel. The treeview moves but the popup edit box does not.
I have done something similar before by binding a function to mousewheel and recalculate all the new x & y location of your hovering widgets.
class EditableDataTable(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.tree = None
self.entryPopup = None
self.list_of_entries = []
...
self.tree.bind("<MouseWheel>", self._on_mousewheel)
def _on_mousewheel(self, event):
if self.list_of_entries:
def _move():
for i in self.list_of_entries:
try:
iid = i.iId
x, y, width, height = self.tree.bbox(iid, column="Col2") #hardcoded to col2
i.place(x=x, y=y+height//2, anchor='w', width=width)
except ValueError:
i.place_forget()
except tk.TclError:
pass
self.master.after(5, _move)
def createPopup(self, row, column):
x,y,width,height = self.tree.bbox(row, column)
# y-axis offset
pady = height // 2
self.entryPopup = EntryPopup(self.tree, row, column)
self.list_of_entries.append(self.entryPopup)
self.entryPopup.place(x=x, y=y+pady, anchor='w', width=width)
Note that this only works on the second column, but should be easy enough to implement for the rest.
You will need to do the math and move the entry widget when the tree is scrolled. I have edited your code and I programmed the scrollbar buttons only. If you click the button the entry widget will scroll with the tree. I did not program the wheelmouse scrolling or dragging the scrollbar. You should be able to figure out the rest.
import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk
class EntryPopup(ttk.Entry):
def __init__(self, parent, itemId, col, **kw):
super().__init__(parent, **kw)
self.tv = parent
self.iId = itemId
self.column = col
self['exportselection'] = False
self.focus_force()
self.bind("<Return>", self.onReturn)
def saveEdit(self):
self.tv.set(self.iId, column=self.column, value=self.get())
print("EntryPopup::saveEdit---{}".format(self.iId))
def onReturn(self, event):
self.tv.focus_set()
self.saveEdit()
self.destroy()
class EditableDataTable(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.tree = None
self.entryPopup = None
columns = ("Col1", "Col2")
# Create a treeview with vertical scrollbar.
self.tree = ttk.Treeview(self, columns=columns, show="headings")
self.tree.grid(column=0, row=0, sticky='news')
self.tree.heading("#1", text="col1")
self.tree.heading("#2", text="col2")
self.vsb = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=self.vsb.set)
self.vsb.grid(column=1, row=0, sticky='ns')
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
self.entryPopup = None
self.curSelectedRowId = ""
col1 = []
col2 = []
for r in range(50):
col1.append("data 1-{}".format(r))
col2.append("data 2-{}".format(r))
for i in range(min(len(col1),len(col2))):
self.tree.insert('', i, values=(col1[i], col2[i]))
self.tree.bind('<Double-1>', self.onDoubleClick)
self.vsb.bind('<ButtonPress-1>', self.func)
def func(self, event):
print(self.vsb.identify(event.x, event.y))
if hasattr(self.entryPopup, 'y'):
item = self.vsb.identify(event.x, event.y)
if item == 'uparrow':
self.entryPopup.y += 20
elif item == 'downarrow':
self.entryPopup.y -= 20
self.entryPopup.place(x=self.entryPopup.x, y=self.entryPopup.y, )
def createPopup(self, row, column):
x, y, width, height = self.tree.bbox(row, column)
# y-axis offset
pady = height // 2
self.entryPopup = EntryPopup(self.tree, row, column)
self.entryPopup.x = x
self.entryPopup.y = y+pady
self.entryPopup.place(x=x, y=y+pady, anchor='w', width=width)
def onDoubleClick(self, event):
rowid = self.tree.identify_row(event.y)
column = self.tree.identify_column(event.x)
self.createPopup(rowid, column)
root = tk.Tk()
for row in range(2):
root.grid_rowconfigure(row, weight=1)
root.grid_columnconfigure(0, weight=1)
label = tk.Label(root, text="Double-click to edit and press 'Enter'")
label.grid(row=0, column=0, sticky='news', padx=10, pady=5)
dataTable = EditableDataTable(root)
dataTable.grid(row=1, column=0, sticky="news", pady=10, padx=10)
root.geometry("450x300")
root.mainloop()
I have simpler solution than tracking mouse events:
self.tree.configure(yscrollcommand = self.ScrollTree)
def ScrollTree(self, a, b):
if self.entryPopup is not None:
pos = self.tree.bbox(self.entryPopup.iid , 'value')
# if cell visible
if pos != '':
self.entryPopup.place(x=pos[0], y=pos[1], width = pos[2], height = pos[3])
else:
self.entryPopup.place_forget()
# update attached scrollbar
self.vsb.set(a, b)

tkinter.Toplevel size automatically fit its widgets

I have made my custom infobox class, InfoBox, that I am using in my application. The tk.messagebox.showinfo did not suit my needs to the poor shape. But InfoBox does not adjust its size to fit the widgets I place inside. How can I make it as small as possible without cutting the widgets?
The class receives a string, msg, and a PhotoImage object, image, which are placed in the InfoBox. I added a screenshot of one such InfoBox.
class InfoBox(tk.Toplevel):
def __init__(self, parent, msg, image):
tk.Toplevel.__init__(self, parent)
self.parent = parent
self.msg = msg
self.image = image
self.title = "Gassy"
self.font = font.Font(family="Optima", size=20)
frame_left = tk.Frame(self)
frame_right = tk.Frame(self)
frame_left.grid(row=0, column=0, sticky=tk.NSEW)
frame_right.grid(row=0, column=1, sticky=tk.NSEW)
tk.Label(frame_left, image=self.image).grid(row=0, column=0, sticky=tk.N)
textbox = tk.Text(frame_right, font=self.font)
textbox.grid(row=0, column=0)
textbox.insert(tk.END, self.msg)
textbox.config(state=tk.DISABLED)
tk.Button(frame_left, text="Den er grei!", font=self.font, command=self.destroy).grid(row=1, column=0)
As #kevin mentioned, it works as intended, the textwidget is mostly empty and occupies a large blank area, this is what makes you think that the geometry manager is not shrinking the window to the widgets.
this:
(I removed the images and fonts that were not provided, and unnecessary)
import tkinter as tk
class InfoBox(tk.Toplevel):
def __init__(self, parent, msg):
tk.Toplevel.__init__(self, parent)
self.parent = parent
self.msg = msg
self.title = "Gassy"
frame_left = tk.Frame(self)
frame_right = tk.Frame(self)
frame_left.grid(row=0, column=0, sticky=tk.NSEW)
frame_right.grid(row=0, column=1, sticky=tk.NSEW)
# textbox = tk.Text(frame_right)
# textbox.grid(row=0, column=0)
# textbox.insert(tk.END, self.msg)
# textbox.config(state=tk.DISABLED)
tk.Button(frame_left, text="Den er grei!", command=self.destroy).grid(row=1, column=0)
root = tk.Tk()
info = InfoBox(root, '123 ' * 1000)
root.mainloop()
produces that:
whereas that:
import tkinter as tk
class InfoBox(tk.Toplevel):
def __init__(self, parent, msg):
tk.Toplevel.__init__(self, parent)
self.parent = parent
self.msg = msg
self.title = "Gassy"
frame_left = tk.Frame(self)
frame_right = tk.Frame(self)
frame_left.grid(row=0, column=0, sticky=tk.NSEW)
frame_right.grid(row=0, column=1, sticky=tk.NSEW)
textbox = tk.Text(frame_right)
textbox.grid(row=0, column=0)
textbox.insert(tk.END, self.msg)
textbox.config(state=tk.DISABLED)
tk.Button(frame_left, text="Den er grei!", command=self.destroy).grid(row=1, column=0)
root = tk.Tk()
info = InfoBox(root, '123 ' * 1000)
root.mainloop()
produces this:
Clearly, the Toplevel subclass adjusts its size to the widgets it contains
The test widget is displayed at a certain size, regardless of its content. The Toplevel resizes around the widgets, NOT around whatever is inserted in the text widget; like with a text processor rudimentary window, the text processor does not shrink or expand as text is typed or edited. The same applies here.
The keyword args width and height allow to configure the size (as a number of characters, or lines) of a text widget

Categories

Resources