ttk Treeview, get item's bbox after scrolling into view - python-3.x

I am working on an editable tkinter.ttk.Treeview subclass. For editing I need to place the edit widget on top of a choosen "cell" (list row/column). To get the proper coordinates, there is the Treeview.bbox() method.
If the row to be edited is not in view (collapsed or scrolled away), I cannot get its bbox obviously. Per the docs, the see() method is meant to bring an item into view in such a case.
Example Code:
from tkinter import Tk, Button
from tkinter.ttk import Treeview
root = Tk()
tv = Treeview(root)
tv.pack()
iids = [tv.insert("", "end", text=f"item {n}") for n in range(20)]
# can only get bbox once everything is on screen.
n = [0]
def show_bbox():
n[0] += 1
iid = iids[n[0]]
b = tv.bbox(iid)
if not b:
# If not visible, scroll into view and try again
tv.see(iid)
# ... but this still doesn't return a valid bbox!?
b = tv.bbox(iid)
print(f"bbox of item {n}", b)
btn = Button(root, text="bbox", command=show_bbox)
btn.pack(side="bottom")
root.mainloop()
(start, then click the button until you reach an invisible item)
The second tv.bbox() call ought to return a valid bbox, but still returns empty string. Apparently see doesnt work immediately, but enqeues the viewport change into the event queue somehow. So my code cannot just proceed synchronously as it seems.
How to solve this? Can see() be made to work immediately? If not, is there another workaround?

The problem is that even after calling see, the item isn't visible (and thus, doesn't have a bounding box) until it is literally drawn on the screen.
A simple solution is to call tv.update_idletasks() immediately after calling tv.see(), which should cause the display to refresh.
Another solution is to use tv.after to schedule the display of the box (or the overlaying of an entry widget) to happen after mainloop has a chance to refresh the window.
def print_bbox(iid):
bbox = tv.bbox(iid)
print(f"bbox of item {iid}", bbox)
def show_bbox():
n[0] += 1
iid = iids[n[0]]
tv.see(iid)
tv.after_idle(print_bbox, iid)

Related

Is it possible to make Tkinter scrollbars move independently of each other in different Toplevel windows?

Imagine there are two Tkinter.Toplevel() windows, called Window_1 and Window_2, which can be opened by clicking the same button (lets called Button_0).
Button_0 is pressed and Window_1 pops up. In Window_1, I can scroll up and down using a mouse pad (MAC OS). After that, I left Window_1 open.
Button_0 is pressed again and Window_2 pops up, while Window_1 stays open. In Window_2, I can again scroll up and down.
Now, I go back to Window_1 and try to scroll using mouse pad, contents in Window_1 DO NOT MOVE, but contents in Window_2 DO MOVE.
Then I close Window_2, and try to scroll on Window_1, this time I got error messages asking for a canvas on Window_2.
I did bind function,
def on_vertical(canvas,event):
canvas.yview_scroll(-3 * event.delta, 'units')
to a canvas inside each windows. As far as I know about the error, it seems that this function could not be used twice at the same time (both windows are opened).
I would like the way that when both Windows stay open. While on each window, I can scroll up-down while the another one do not move. Is it possible to code that?
This is the code example (please do noted that the Window name is not corrected label.)
from tkinter import *
######################## FUNCTIONS (DEF) ########################
def on_vertical(canvas,event):
canvas.yview_scroll(-3 * event.delta, 'units')
######################## FUNCTIONS (CLASS) ########################
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
#INITIAL WINDOW
def init_window(self):
self.master.title("Main Window")
self.pack(fill=BOTH, expand=1)
Button(self, text="Button_0",command = self.load_and_print).place(x = 7, y = 95)
# creating a button instance
Button(self, text="EXIT PROGRAM", command=self.client_exit).place(x=500, y=250)
#OPEN A NEW WINDOW CONTAINING STOCK LISTS
def load_and_print(self):
new_window = Toplevel(self)
new_window.title("Window")
canvas = Canvas(new_window, width = 800, height = 500, scrollregion = (0, 0, 0, 2500))
frame = Frame(canvas)
vbar = Scrollbar(new_window, orient = VERTICAL, command = canvas.yview)
vbar.pack(side = RIGHT,fill = Y)
canvas.create_window(0,0, window = frame, anchor = NW)
canvas.config(yscrollcommand = vbar.set)
canvas.pack(side = TOP,expand = True,fill = BOTH)
canvas.bind_all('<MouseWheel>', lambda event, canvas=canvas: on_vertical(canvas,event))
#MAKE PROGRAM EXIT
def client_exit(self):
exit()
######################## MAIN PROGRAMME ########################
#call window
root = Tk()
#size of the window
root.geometry("700x300")
app = Window(root)
root.mainloop()
root.update()
The problem is that you are using bind_all instead of bind for the mousewheel event.
Because you're using bind_all, each time you create a new window it replaces the old binding with a new binding. No matter which window gets the event, your function will always only work for the last window to be created. And, of course, when that window is destroyed then the mouse binding will throw an error since the canvas no longer exists.
Using bind
One solution is simple: use bind instead of bind_all.
canvas.bind_all('<MouseWheel>', lambda event, canvas=canvas: on_vertical(canvas,event))
Using bind_all
If you want the benefits of bind_all -- namely, that the scrolling works even if the mouse is over some other widget, you need to modify on_vertical to figure out which canvas to scroll at the time that it is running instead of having the canvas being passed in.
You can do that with a little bit of introspection. For example, the event object knows which widget received the event. From that you can figure out which window the mouse is in, and from that you can figure out which canvas to scroll.
For example, move the binding up to the __init__ and change it like this:
self.bind_all('<MouseWheel>', on_vertical)
Next, change on_vertical to figure out which canvas to scroll. In the following example I assume each toplevel has exactly one canvas and that you always want to scroll that canvas (ie: you lose the ability to scroll text widgets and listboxes)
If that's not the case, you can add whatever logic you want to figure out which widget to scroll.
def on_vertical(event):
top = event.widget.winfo_toplevel()
for child in top.winfo_children():
if child.winfo_class() == "Canvas":
child.yview_scroll(-3 * event.delta, 'units')
break

tkinter canvas - extract object id from event?

Is there a way I can extract the canvas object's id from an event?
For example, I'd like to add an item to a canvas, and bind to it - but if I have multiple items of them on my canvas, I need to distinguish between them.
def add_canvas_item(self,x,y):
canvas_item_id = self.canvas.create_oval(x-50,y-50,x+50,y+50, fill='green')
self.canvas.tag_bind(canvas_item_id ,"<ButtonPress-1>",self.stateClicked)
def itemClicked(self,event):
print("Item XYZ Clicked!") <- Where XYZ is the ID of the item
I have some very "hacky" ways around this (keep track of the mouse, and ask the canvas for the nearest item to that point) but that doesn't seem like the "best" way.
Is there a better way?
You can use the find_withtag() function which returns the clicked item as in the example below:
from tkinter import *
root = Tk()
canvas = Canvas(root)
canvas.pack()
def itemClicked(event):
canvas_item_id = event.widget.find_withtag('current')[0]
print('Item', canvas_item_id, 'Clicked!')
def add_canvas_item(x,y):
canvas_item_id = canvas.create_oval(x-50,y-50,x+50,y+50, fill='green')
canvas.tag_bind(canvas_item_id ,'<ButtonPress-1>', itemClicked)
add_canvas_item(100,100) # Test item 1
add_canvas_item(250,150) # Test item 2
root.mainloop()
Brief description at Tracking Mouse Actions for Many Canvas Objects

PyQt QScrollArea doesn't display widgets

I am somewhat new to GUI programming and very new to PyQt, and I'm trying to build a GUI that displays a list of questions. I have created a QuestionBank class that subclasses QWidget and overrides the .show() method to display the list properly. I have tested this alone and it works correctly. However, the list of questions can be quite long, so I've been trying to make it scrollable. Rather than add a QScrollBar to the widget and then set up the event triggers by hand, I've been trying to my QuestionBank widget in a QScrollArea based on the syntax I've seen in examples online. While the scroll area shows up fine, it does not at all display the question bank but rather just shows a blank outline.
The QuestionBank class looks like this:
class QuestionBank(QWidget):
BUFFER = 10 # space between questions (can be modified)
def __init__(self, parent, questions):
# `parent` should be the QWidget that contains the QuestionBank, or None if
# QuestionBank is top level
# `questions` should be a list of MasterQuestion objects (not widgets)
QWidget.__init__(self, parent)
self.questions = [MasterQuestionWidget(self, q) for q in questions]
self.bottomEdge = 0
def show(self, y=BUFFER):
QWidget.show(self)
for q in self.questions:
# coordinates for each each question
q.move(QuestionBank.BUFFER, y)
q.show()
# update y-coordinate so that questions don't overlap
y += q.frameGeometry().height() + QuestionBank.BUFFER
self.bottomEdge = y + 3 * QuestionBank.BUFFER
# ... other methods down here
My code for showing the scroll bar looks like this:
app = QApplication(sys.argv)
frame = QScrollArea()
qs = QuestionBank(None, QFileManager.importQuestions())
qs.resize(350, 700)
frame.setGeometry(0, 0, 350, 300)
frame.setWidget(qs)
frame.show()
sys.exit(app.exec_())
I have tried many variants of this, including calling resize on frame instead of qs, getting rid of setGeometry, and setting the parent of qs to frame instead of None and I have no idea where I'm going wrong.
If it helps, I'm using PyQt5
Here is the question bank without the scroll area, to see what it is supposed to look like:
Here is the output of the code above with the scroll area:
This variation on the code is the only one that produces any output whatsoever, the rest just have blank windows. I'm convinced its something simple I'm missing, as the frame is obviously resizing correctly and it obviously knows what widget to display but its not showing the whole thing.
Any help is much appreciated, thank you in advance.

Change the label's text everytime a button is pressed

I'm doing a PYTHON table using FOR, in TKINTER, and I would like every time a new number is placed in ENTRY, the label changes to the new table. For example, a number will be placed in the ENTRY and the person will click the TAB button, when it is clicked, the table will appear, but if the person wants another number, and click again, the new table will go down from the previous one. My solution was to create a button that erases the previous table, but when the button is pressed, only the last multiplication is deleted. I would like to know how I click the tabuada button, and the previous one erases the new one without using another button .Get the code and a photo below, Thanks. Obs.: First photo shows reset button working, but it just erase the last multiplication,second photo shows the whole multiplication.
from tkinter import *
import tkinter as tk
win=tk.Tk()
win.title('Table')
lb=Label(win,text='Type a number:',font='Helvetica 12 bold')
lb.pack()
e=Entry(win)
e.pack()
def click():
global c
c=e.get()
print('requested number ',c)
for b in (range(0, 11)):
global lb2
lb2=Label(text='{} x {} = {} '.format(c, b, int(b)*int(c)))
lb2.pack()
def reset():
lb2['text'] = ' '
bt1=Button(win,text='GO',bg='lightblue',command=click)
bt1.pack()
bt2=Button(win,text='RESET',bg='lightblue',command=reset)
bt2.pack()
win.mainloop()
erasing:
whole multiplication:
Here are some fixes for your code; it was not entirely clear what you exactly meant by: "the new table will go down from the previous one.", so I went with having the new table replacing the previous one.
c was not defined in your code and that threw an exception.
I placed the construction of the label inside a function make_label that is called from the main block, and from click(), to rebuild it when a new number is requested.
reset was missing a call to pack on the label, to update the text displayed.
I think that should help you get started in the right direction; let me know if something is unclear.
edit:
I modified reset so the label is destroyed and re-created from view, thus removing the growth in size of the window.
from tkinter import *
import tkinter as tk
win=tk.Tk()
win.title('Table')
lb=Label(win,text='Type a number:',font='Helvetica 12 bold')
lb.grid(row=0, column=0)
lb2 = Label(text='')
e=Entry(win)
e.grid(row=1, column=0)
c = 2
def click():
global c
c = e.get()
print('requested number ', c)
reset()
make_label(c)
def make_label(c):
global lb2
txt = []
for b in (range(0, 11)):
txt.append('{} x {} = {} '.format(c, b, int(b)*int(c)))
text = '\n'.join(txt)
lb2 = Label(text=text)
lb2.grid(row=4, column=0)
def reset():
global lb2
lb2.destroy()
lb2 = Label()
lb2.grid(row=4, column=0)
make_label(c)
bt1=Button(win,text='GO',bg='lightblue',command=click)
bt1.grid(row=2, column=0)
bt2=Button(win,text='RESET',bg='lightblue',command=reset)
bt2.grid(row=3, column=0)
win.mainloop()

tkinter python maximize window

I want to initialize a window as maximized, but I can't find out how to do it. I'm using python 3.3 and Tkinter 8.6 on windows 7. I guess the answer is just here: http://www.tcl.tk/man/tcl/TkCmd/wm.htm#m8
but I have no idea how to input it into my python script
Besides, I need to get the width and height of the window (both as maximised and if the user re-scale it afterwards), but I guess I can just find that out myself.
You can do it by calling
root.state('zoomed')
If you want to set the fullscreen attribute to True, it is as easy as:
root = Tk()
root.attributes('-fullscreen', True)
However, it doesn't show the title bar. If you want to keep it visible, you can resize the Tk element with the geometry() method:
root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (w, h))
With winfo_width() and winfo_height() you can get the width and height or the window, and also you can bind an event handler to the <Configure> event:
def resize(event):
print("New size is: {}x{}".format(event.width, event.height))
root.bind("<Configure>", resize)
To show maximized window with title bar use the 'zoomed' attribute
root = Tk()
root.attributes('-zoomed', True)
I've found this on other website:
import Tkinter
MyRoot = Tkinter.Tk()
MyRoot.state("zoomed")
MyRoot.mainloop()
This solved my problem.
The first approach is to use the root.state('zoomed'), but is not supposed to be universally available. It works on Windows, and on my Ubuntu machine. However, under my Arch machine it doesn't.
The second is to first get the maxsize, and then set geometry manually, like:
m = root.maxsize()
root.geometry('{}x{}+0+0'.format(*m))
This works on most machines, but not on all. For example, under my Arch the maxsize() returns (1425, 870), while the real geometry of maximized window should be (1440, 848). So, you also couldn't rely on it.
And the third, in my opinion the best approach is to use root.wm_attributes('-zoomed', 1). It is universally available and seems to be the safest. On some machines in could zoom only by width or by height, but comparing to previous method, this one would never give you a window partly ouside of the screen.
Finally, if you want a fullscreen, not just zoomed window, use root.wm_attributes('-fullscreen', 1). It provides a native link to window manager's behavior, thus working much better, than playing with overrideredirect and setting geometry by hand (which on some platforms could lead to unmanaged window, which could be closed only by its own interface or killing the process, won't show on the taskbar, etc...)
The most pythonic is" root.wm_state('zoomed'), as mentioned by #J.F.Sebastian
I recently ran into a similar issue where a library I was supporting needed to add Windows 10 as a development target also. Thanks to the information I found here, This is what we're doing now:
class INI_Link:
"""A connector class between a value stored in an ini file, and a value stored elsewhere that can be get and set with two helper functions."""
def __init__(self, getter, setter, varname, inigroup="Settings", inifile=''):
"""Remember that getter is called first to provide the default value.
Then the ini value is read if available, if not the default value is used."""
self._get = getter
self._set = setter
self._save = lambda value :inidb(inifile)[inigroup].__setitem__(varname, getter())
self._load = lambda :inidb(inifile)[inigroup].get(varname, getter())
#first load
self._lastvalue = self._load()
print(self._lastvalue)
self._set(self._lastvalue)
self._callbacks=[]
def trace(self, callback, mode='w'):
"""this only traces for .value.set() not for changes to the underlying value in either location.
if you never touch this again until .commit() at the end of your program, then it will never trigger until then.
call .probe() to force to check for changes without returning anything."""
self.callbacks.append(callback)
def probe(self):
"""check for changes, if there have been any, allert all traces."""
self._monitor(self._get())
def __get__(self):
value = self._get()
self._monitor(value)
return value
def __set__(self, value):
self._set(value)
self._save(value)
self._monitor(value)
def _monitor(value):
"helper to dispatch callbacks"
if value != self._lastvalue:
self._lastvalue = value
for cb in self._callbacks:
try:
cb()
except:
pass
def commit(self):
"""Call this right before getter is no longer useful."""
self._save(self._get())
And then in the main window class's __init__()
self._geometry = INI_Link(self.tkroot.geometry, self.tkroot.geometry, "window_geometry")
try:
#umbuntu and others, not arch
self._zoomed = INI_Link(lambda:self.tkroot.wm_attributes('-zoomed'),
lambda z: self.tkroot.wm_attributes('-zoomed', z)
, "window_zoomed")
except:
#windows and others, not umbuntu
self._zoomed = INI_Link(lambda: self.tkroot.state() == 'zoomed',
lambda z: self.tkroot.state(['normal','zoomed'][z])
, "window_zoomed")
and then when the window is being closed:
#save zoomed state.
self._zoomed.commit()
try:
if self.tkroot.wm_attributes('-zoomed'):
self.tkroot.wm_attributes('-zoomed', False)
self.tkroot.update()
except:
if self.tkroot.state() != 'normal':
self.tkroot.state('normal')
self.tkroot.update()
#save window size in normal state
self._geometry.commit()
With TkAgg as backend this is the only combination that maximized the window without fullscreen:
win_manager = plt.get_current_fig_manager()
win_manager.window.state('zoomed')
win_manager.full_screen_toggle()

Resources