Every Item of Tkinter Canvas widget has a unique item id. I can delete the item by using
canvas.delete(itemId)
Now how do I get back the item on the Canvas assuming I have kept the itemId intact?
canvas.add(itemId) # something like this but add is not a canvas method
I read that it can be done in Tcl/Tk but did not find any equivalent reference for tkinter.
The Canvas widget has no add method, but the different create_ methods. If you have already deleted an item and you want to "restore" it, you should get the options of the item before that and then create a new one with the values you have retrieved.
When you delete it, it's gone. You can't get it back. The item id is just an identifier, not an actual object.
Related
Referencing to an old thread :
Dynamically Add Values To Tkinter Menubutton (using list)
when it comes to menubuton in tkinter, i'm trying to use the same code provided in the answer to dynamically add values to menu in tkinter, given the amount of items i want in my menu.
This can be done by using a list and a dictionary as follows:
menubutton = Menubutton(root, text = "Select")
menubutton.menu = Menu(menubutton)
menubutton["menu"]= menubutton.menu
# main list holding menu values
list1 = ['a', 'b', 'c']
# Creating a dictionary
dict2 = {}
# Add key-value pairs to dictionary
for i in range(0, len(list1)):
temp = {'var'+str(i): list1[i]}
dict2.update(temp)
# Finally adding values to the actual Menubutton
for i in range(0, len(list1)):
menubutton.menu.add_checkbutton(label = dict2['var'+str(i)], variable = list(dict2.keys())[i])
menubutton.pack()
My question with this now is, how do I control the variables (i.e if i want to do a .get() or .set(0) or similar), how do i reference to it considering that my variable is being generated within the for loop as it is what is adding the actual items to the menu based in the contents of the list?
and on the same note, how do I check (just for sake of simplicity, how do I print the selected variables) (and values, i dont see for example onvalue inside the checkbutton in this case, i'm assuming I'd have to pre-assign a value to each specific item of the list, and then have this value be generated based on the index of each item being created during the for loop
Thanks in advance,
If you have any sugestions on a different widget that might be more useful and convenient for this purpose (I wanted a multiple selection checkbox but thats doesnt seem to be a thing in tkinter, so menubutton is the thing I came the closest to that outcome).
Nonetheless I'd still appreciate an explanation to the above, always good to learn...
I am learning Python w/ Tkinter and I recently learned the difference between the reference and the name/instance of a widget. The reference is the string you assign to a widget (which can be changed later on), but the name seems to be the actual identity of the widget (which is immutable). Essentially it seems as though the reference is a nickname of a widget because it can change overtime and be different depending on who you are talking to, while the actual name of the widget on the widget's drivers license is always the same. Specifically, in this line of code...
sample_frame = Frame(root, name = 'frame1', bg = 'blue', height = 50, width = '50')
"sample frame" is the reference, while 'frame1' is the name.
Unless I specifically assign the string 'frame1' as the name of this frame, python automatically generates a number sequence as its name. In order to view the name of any widget you just have to add...
print(str(sample_frame))
(the output in this example is .frame1)
So in Tkinter if I wanted to place this frame in my GUI i would have to pack/grid/place it in the following line like so...
sample_frame.pack()
But what I would like to do is call the pack method on this frame widget by its name rather than its reference. Something like this...
frame1.pack() #or
.frame1.pack() #because of that period
The problem is that Python claims frame1 was never defined, and .frame1 is invalid syntax. Does anybody know how to do something like this? Thanks.
For broader context I am doing this because I iterated the creation of 21 different frames and placed them in a 3x7 grid. Because of this all 21 frames have an identical reference. BUT, I made sure to make the name of each frame corresponds with its position.
The name= option sets the name of the widget within the Tcl environment that actually implements the GUI - it has no effect on the Python side. The only reason I can think of for doing this is that it might make Tcl error messages somewhat easier to read (the auto-generated widget name that you'd otherwise get is not particularly meaningful).
As always, the proper way to deal with multiple objects created in a loop is to store them in a container of some sort. In your case, it could be a 21 element list, a nested list (widget[row][column]), or perhaps a dict indexed by tuples (widget[row, column]).
While I fully agree with jasonharper's answer that you should keep a proper reference to the widgets and I do not recommend using what I'm about to explain, there actually is a way to achieve what you're asking. There's a widget method called nametowidget(), which returns the widget object when you give it a name. Note that you should call the method on the object (Tk, Toplevel, Frame) that contains the widget you're looking for.
So following your example, this works:
from tkinter import *
root = Tk()
sample_frame = Frame(root, name = 'frame1', bg = 'blue', height = 50, width = '50')
root.nametowidget('frame1').pack()
root.mainloop()
And if you would do the same with a button inside the frame you should do:
sample_button = Button(sample_frame, text='Button', name='button1')
sample_frame.nametowidget('button1').pack()
I have a TreeView widget that I inserted a few items into, and applied a few tags selectively on some of those items. Now I want to bind a click event to all items in the widget, but the bind syntax looks like this:
treeView.tag_bind(tag_name, event_sequence, click_handler)
My problem is I want to do this for all tags, and also for non-tagged items. Is there something like .tag_bind_all?
Use a list or function. Assuming to you want to bind all tags the same:
for this_tag in [tag_name1, tag_name2, tag_name3]:
treeView.tag_bind(this_tag, event_sequence, click_handler)
I figured this out, this did it:
treeView.bind('<<TreeviewSelect>>', lambda *x:self.__treeViewItemSelected())
Then inside the method I can do :
item_id = treeView.focus()
value = treeView.item(item_id)
I have a GUI built using PyQt4 where I use matplotlib (FigureCanvas) to plot several plots using multiple canvases (this is intentional rather than using subplots). for each canvas I use method:
self.canvas_xx.mpl_connect('scroll_event', self.on_mouse_scroll)
where xx represents the iteration of the canvas to get a signal to perform some action. I want to be able to reference the canvas by its name rather than using:
ylabel = event.inaxes.axes.get_ylabel().split(' ')[0]
where I use the longer method of referncing the ylabel name of each graph.
I looked under the event method using: dir(event) and there is a method called "canvas", but there is no apparent method to get the name of the canvas.
Any ideas?
I am not quite sure what you mean by name, but you can get a a reference to the canvas object via
event_canvas = event.inaxes.axes.figure.canvas
and canvas events are hashable, so you can use them as keys in a dict
other_thing = pre_populated_dict[event_canvas]
to keep track of what ever other data you want to about a given canvas in your code.
In python there is, in general, not a clean way to get the names of references to an object (it can be done, but you shouldn't).
when i added an item in a qlistwiget and reaches the bottom. A scroll bar appears, how can i ensurevisible an item that was newly added from the qlistwidget? Or how can i get the focus to the last index?
QListWidget inherits from QAbstractItemView, which has the methods you are looking for:
You can use QAbstractItemView.scrollTo(ModelIndex index), using the index of your newly added item.
Alternatively, since your item is always appended to the end of the list, just call QAbstractItemView.scrollToBottom().
After creating the new QListWidgetItem, pass it to QListWidget.scrollToItem to ensure that it becomes visible.
Note that scrollToItem also has a scroll hint parameter that allows fine-tuning of how the item is re-positioned in the list widget.