Tkinter Canvas: Change option without changing others OR set all options again - python

Creating a fairly basic window and trying to keep everything nice and tightly jammed in the window so that there are no gaps between items in the grid requires setting the canvas's border to -2 (annoying, should be 0, but a different complaint for a different day). However, when updating other attributes (in this case bg), that bd attribute gets reset irreparably. Requesting that property returns the -2 it got set to, but the canvas acts like it isn't (i.e., the canvas appears to have a bd value of 0, despite saying it has -2 when asked).
How can one update only one attribute without breaking the bd attribute?
OR,
How can one set all the attributes for that object simultaneously after it already exists similarly to when it was created so that bd actually takes effect?
A simple example that lets you play with it:
import tkinter as tk
from functools import partial
class MyGUI:
def __init__(self, master):
self.master = master
self.buttonx = tk.Button(master, text='goblue', command=partial(self.gocol, 'lightblue'), bg='lightblue')
self.buttonx.grid(row=1,column=0)
self.buttony = tk.Button(master, text='gogrey', command=partial(self.gocol, 'grey'), bg='grey')
self.buttony.grid(row=2,column=0)
self.canvasx_specs = {
'width' : 400,
'height' : 400,
'bg' : 'grey',
'bd' : -2
}
self.canvasx = tk.Canvas(master, **self.canvasx_specs)
self.canvasx.grid(rowspan=9,row=1,column=1)
def gocol(self, col):
## Method 1
self.canvasx['bg']=col
# self.canvasx.configure(bg=col)
## Method 2
# self.canvasx_specs['bg'] = col
# self.canvasx.configureall(**self.canvasx_specs)
top = tk.Tk()
mywin = MyGUI(top)
top.mainloop()
It doesn't appear to matter if you set bd to -2 again, it still acts like it is 0. It also doesn't appear to matter if you use members access or configure function (see Method 1 above), it has the same effect.
I don't want to delete the whole canvas, it may have drawn objects in it already, and I don't want to redraw everything when the background (or some other option) changes.

Canvas (and other widgets) may have two elements - border and highlight.
If you set bd to 0 or -2 then you can still see highlight which you can remove with 'highlightthickness': 0

Related

Tkinter, update widgets real time if list is modified

Let say I've a list of widgets that are generated by tkinter uisng a loop (it's customtkinter in this case but since tkinter is more well known so I think it'd be better to make an example with it), each widgets lie in the same frame with different label text. Here is an example for the code:
x=0
self.scrollable_frame = customtkinter.CTkScrollableFrame(self, label_text="CTkScrollableFrame")
self.scrollable_frame.grid(row=1, column=2, padx=(20, 0), pady=(20, 0), sticky="nsew")
self.scrollable_frame.grid_columnconfigure(0, weight=1)
self.scrollable_frame_switches = []
for i in range(x,100):
switch = customtkinter.CTkSwitch(master=self.scrollable_frame, text=f"CTkSwitch {i}")
switch.grid(row=i, column=0, padx=10, pady=(0, 20))
self.scrollable_frame_switches.append(switch)
My question is, if the list that help generated those widgets change (in this case it's just a loop ranging from 0-100, might change the widgets text, list size..), what would be the best way for real time update the tkinter window contents?
Ps: I've tried to look for my answer from many places but as of right now, the best answer I can come up with is to update the whole frame with same grid but changed list content, I'll put it bellow. Is there any way better than this? Thank you
Like I said before, while the existing answer might work, it might be inefficient since you are destroying and creating new widgets each time there is a change. Instead of this, you could create a function that will check if there is a change and then if there is extra or less items, the changes will take place:
from tkinter import *
import random
root = Tk()
def fetch_changed_list():
"""Function that will change the list and return the new list"""
MAX = random.randint(5, 15)
# Create a list with random text and return it
items = [f'Button {x+1}' for x in range(MAX)]
return items
def calculate():
global items
# Fetch the new list
new_items = fetch_changed_list()
# Store the length of the current list and the new list
cur_len, new_len = len(items), len(new_items)
# If the length of new list is more than current list then
if new_len > cur_len:
diff = new_len - cur_len
# Change text of existing widgets
for idx, wid in enumerate(items_frame.winfo_children()):
wid.config(text=new_items[idx])
# Make the rest of the widgets required
for i in range(diff):
Button(items_frame, text=new_items[cur_len+i]).pack()
# If the length of current list is more than new list then
elif new_len < cur_len:
extra = cur_len - new_len
# Change the text for the existing widgets
for idx in range(new_len):
wid = items_frame.winfo_children()[idx]
wid.config(text=new_items[idx])
# Get the extra widgets that need to be removed
extra_wids = [wid for wid in items_frame.winfo_children()
[-1:-extra-1:-1]] # The indexing is a way to pick the last 'n' items from a list
# Remove the extra widgets
for wid in extra_wids:
wid.destroy()
# Also can shorten the last 2 steps into a single line using
# [wid.destroy() for wid in items_frame.winfo_children()[-1:-extra-1:-1]]
items = new_items # Update the value of the main list to be the new list
root.after(1000, calculate) # Repeat the function every 1000ms
items = [f'Button {x+1}' for x in range(8)] # List that will keep mutating
items_frame = Frame(root) # A parent with only the dynamic widgets
items_frame.pack()
for item in items:
Button(items_frame, text=item).pack()
root.after(1000, calculate)
root.mainloop()
The code is commented to make it understandable line by line. An important thing to note here is the items_frame, which makes it possible to get all the dynamically created widgets directly without having the need to store them to a list manually.
The function fetch_changed_list is the one that changes the list and returns it. If you don't want to repeat calculate every 1000ms (which is a good idea not to repeat infinitely), you could call the calculate function each time you change the list.
def change_list():
# Logic to change the list
...
calculate() # To make the changes
After calculating the time for function executions, I found this:
Widgets redrawn
Time before (in seconds)
Time after (in seconds)
400
0.04200148582458496
0.024012088775634766
350
0.70701003074646
0.21500921249389648
210
0.4723021984100342
0.3189823627471924
700
0.32096409797668457
0.04197263717651367
Where "before" is when destroying and recreating and "after" is only performing when change is needed.
So I've decided that if I want to click a button, that button should be able to update the list. Hence, I bind a non-related buttons in the widget to this function:
def sidebar_button_event(self):
global x
x=10
self.scrollable_frame.destroy()
self.after(0,self.update())
Which will then call for an update function that store the change value, and the update function will just simply overwrite the grid:
def update(self):
self.scrollable_frame = customtkinter.CTkScrollableFrame(self, label_text="CTkScrollableFrame")
self.scrollable_frame.grid(row=1, column=2, padx=(20, 0), pady=(20, 0), sticky="nsew")
self.scrollable_frame.grid_columnconfigure(0, weight=1)
self.scrollable_frame_switches = []
for i in range(x,100):
switch = customtkinter.CTkSwitch(master=self.scrollable_frame, text=f"CTkSwitch {i}")
switch.grid(row=i, column=0, padx=10, pady=(0, 20))
self.scrollable_frame_switches.append(switch)

Moving shapes from one scene/window to another using Python tkinter canvas

Here is a rough example of what I want to do(my code is too long and messy to share here): -
import tkinter as tk
app = tk.Tk()
w, h = 600, 600
canvas = tk.Canvas(app, width = w, height = h)
canvas.pack()
Rec1 = canvas.create_rectangle(0, 0, 100, 100, fill = 'blue', tag = 'move_to_next_window')
Rec2 = canvas.create_rectangle(100, 100, fill='green', tag = 'dont_move_to_next_window')
app.mainloop()
I am sorry if I messed up a couple lines but this program should run by creating 2 rectangles. What I need help with is if I initiate a brand new window which is running off different code, how would I move Rec1 and its position to the other window. If its possible, could I copy all of the object's properties in the second window? Thank you for taking the time to read this (the second window can also use the tkinter canvas).
What I need help with is if I initiate a brand new window which is running off different code, how would I move Rec1 and its position to the other window.
You can't move canvas items from one canvas to another. Your only option is to delete the item in the first canvas and add a new item in the other canvas.
If its possible, could I copy all of the object's properties in the second window?
Yes, you can use the itemconfigure method to get all of the properties of a canvas object, you can use coords to get the coordinates, and you can get the type with type method.
Here's an example function that copies a rectangle from one canvas to another.
def copy_canvas_item(source, item_id, destination):
item_type = source.type(item_id)
coords = source.coords(item_id)
# N.B. 'itemconfigure' returns a dictionary where each element
# has a value that is a list. The currently configured value
# is at index position 4
attrs = {x[0]: x[4] for x in source.itemconfigure(item_id).values()}
if item_type == "rectangle":
item_id = destination.create_rectangle(*coords, attrs)
return item_id

tkinter - resizing empty frame

How do you force a frame to get window_height 0?
the general case where my problem occurs:
import Tkinter as Tk
class App(Tk.Frame):
def __init__(self, master):
Tk.Frame(self, master)
self.place_holder = Tk.Frame(master=self)
self.content = Tk.Frame(master=self)
self.place_holder.pack()
self.content.pack(side=Tk.RIGHT)
Tk.Button(master=self,command=self.add_something).pack(side=Tk.TOP)
self.to_destroy = []
def add_something(self):
foo = Tk.button(master=self.place_holder, command=self.destroy_last)
self.too_destroy.append(foo)
def destroy_last(self):
self.to_destroy[-1].destroy()
the problem:
As I add more elements to the place_holder, it rescales nicely.
When I remove elements from the place_holder, it rescales nicely.
EXCEPT when I remove the last element.
Before i added anything, even when i do place_holder.pack(), it will not show. But after removing the last element, the place_holder will keep the size of this last element. Is there a way to hide the place_holder again untill i add content again?
example image
The empty container at the bottom left does not contain any elements, but still has the size of the last element in it, how can i get this to disappear without removing it (i want it again in the same place)?
What is happening is that when you remove the last widget, pack no longer is managing the frame so it isn't responsible for setting the frame size.
The simplest solution is just to temporarily pack a 1x1 pixel frame, which wil cause the placeholder frame to shrink.
There's no way to make a frame of zero pixels, so this method will always result in a one pixel tall/wide area for the placeholder. If you don't want that one pixel, you can install call pack_forget on the placeholder to completely remove it from the display, and then use pack with suitable options to re-add it when you put something in it.
Example:
def destroy_last(self):
self.to_destroy.pop().destroy()
if len(self.to_destroy) == 0:
tmp = Tk.Frame(self.place_holder, width=1, height=1, borderwidth=0)
tmp.pack()
self.place_holder.update()
tmp.destroy()

Programatically add and remove tkinter python labels causes IndexError: list index out of range

Sorry for the vague title but I didn't know how to explain myself better. Basically what I try to do in tkinter here is adding and removing labels. The label value gets updated so that I always have an increment of 1 even though I deleted a label in the beginning. If I generate labels and delete them from the bottom up I have no problems but it I delete one from the middle and then try to clean my list I get an error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1536, in __call__
return self.func(*args)
File "/Users/XXXX/Helper/development/dynamicListLabels.py", line 21, in <lambda>
labelList[index].append(ttk.Button(root, text="Remove", command=lambda: removeLabel(labelList[index][0], index)))
IndexError: list index out of range
My python code looks like this:
#!/usr/bin/python
from Tkinter import *
import ttk
def removeLabel(labelToRemove, bla):
labelList[labelToRemove.get()][1].destroy()
labelList[labelToRemove.get()][2].destroy()
del labelList[labelToRemove.get()]
for label in labelList:
index = labelList.index(label)
label[0].set(index)
def addNewLabel():
labelList.append([IntVar()])
index = len(labelList) - 1
labelList[index][0].set(index)
labelList[index].append(ttk.Label(root, textvariable=labelList[index][0]))
labelList[index].append(ttk.Button(root, text="Remove", command=lambda: removeLabel(labelList[index][0], index)))
labelList[index][1].grid(column=0)
labelList[index][2].grid(column=1, row=labelList[index][1].grid_info()['row'])
root = Tk()
labelList = []
ttk.Button(root, text="add label", command=addNewLabel).grid(column=1, row=0)
root.mainloop()
And my GUI looks like this:
Thanks for your help!
Design
The main problem comes when dealing with different indexes. Trying to manipulate them carefully leads to complicated operations resulting in a long and inefficient code. To remedy to this problem, we simply get rid of them and take advantage of the label class variable Tkinter.IntVar() you already are using. This gives us full control of the labels and associated widgets.
An other efficient decision to take that prevents from getting lot of headache is to attach each (label, button) couple widgets to a unique Tkinter.Frame() instance. This offers the advantage of deleting the frame using destroy() method leading automatically to the destruction of the widgets it contains. In the same time, this keeps the look of your GUI and makes your it scalable as it offers you the possibility to add more widgets.
Designing addNewLabel()
There is nothing new here compared to your original code except, as I said in 2. each (label, button) couple will be drawn into a single and unique Tkinter.Frame() instance. Of course, the list frames must be declared global in this method.
Designing removeLabel()
From 1. the only argument we need to pass to removeLabel() is the Tkinter variable (var in the code below) inherent to the label we want to get rid of.
We need then to loop over list of frames (frames in the code below) using winfo_children() to seek for the label which has the text variable we are looking for.
Note that because I draw the label before the button inside individual frames, winfo_children() returns as first widget list element the label
winfo_children():
Returns a list containing the path names of all the children of window. Top-level windows are returned as children of their logical
parents. The list is in stacking order, with the lowest window first,
except for Top-level windows which are not returned in stacking order.
Use the wm stackorder command to query the stacking order of Top-level
windows.
This is why it is correct to write : if frame.winfo_children()[0].var == var and destroy the frame that contains the label which satisfies this condition.
Solution
Here is the program. I commented the lines which I think deserve to be commented:
'''
Created on Jun 25, 2016
#author: billal begueradj
'''
from Tkinter import *
import ttk
def removeLabel(var):
global frames
z = -1
# Loop over the list of rames
for frame in frames:
z = z + 1
# Check the text variable of the label of this frame
if frame.winfo_children()[0].var == var:
# Destroy the related frame
frame.destroy()
# Update the size of the list of frames
frames = frames[:z] + frames[z+1:]
# Do not forget to always rest this flag back to -1
z = -1
# Update the labels' numbers
r = 0
for frame in frames:
frame.winfo_children()[0].var.set(r)
r = r + 1
def addNewLabel():
global frames, i
var = IntVar()
frame = Frame(root)
i = i + 1
frame.grid(row=i, column=0)
var.set(len(frames))
l = ttk.Label(frame, textvariable=var)
l.grid(row=0, column=0)
l.var = var
b = ttk.Button(frame, text="Remove", command=lambda: removeLabel(var))
b.grid(row=0, column=1)
frames.append(frame)
if __name__ == '__main__':
root = Tk()
frames = []
i = 1
ttk.Button(root, text="add label", command=addNewLabel).grid(column=0, row=0)
root.mainloop()
Demo
Let us create 6 labels:
Now let us delete the label number 3. You can see that the numbering of the labels is automatically updated:
Now let us add a new label. You can see the newly added label has a number which is consecutive to the last existing label number in the list:
Note that the length of the list is updated all the time as you wanted.

Unexpected label width value

i am reading the width of a label at three different times and only one of them is producing the correct output.. code:
from tkinter import *
def getwidth(string):
print(string+str(lbl1.winfo_width()))
root = Tk()
lbl1 = Checkbutton(root, text="test text")
lbl1.grid(row=0,rowspan=2)
print("first "+str(lbl1.winfo_width()))
getwidth("second ")
btn = Button(root, text="GO", command=lambda x="third ": getwidth(x))
btn.grid(row=2)
root.mainloop()
How can i read the correct width (69) during the first two outputs without having to rely on the button command? Thanks
current outputs are:
first 1
second 1
third 69
Well, unfortunately, you can't. The first two times are done before the window is loaded (which causes it to return the default value of 1 since the label isn't drawn yet). The third time is done after the window is loaded (the label is drawn), so it returns the correct number.
You have to remember that, until you call root.mainloop and load the window, the widgets are not placed on the screen. Sure, they exist behind the scenes (otherwise a NameError would be thrown), but they are not on the screen and taking up space yet. Thus, when you try to see how much space they are taking up, you get the default number of 1.

Categories