Reputation: 23
It's my first post so I want to thanks the community. I never had to ask my own question until now because of your experience.
Here is my question:
Doing this i was hopping that, using the 'name' variable value, i'll be able to, for exemple, delete/configure/move the objects. But no. My object remains linked to 'name' and not 'objectx'. Python returns me 'NameError: name 'object2' is not defined'
Does someone know a solution for me to build a link between an canvas object and keep it to interact with it?
Many thanks
import tkinter as tk
def popup(event):
print('Got object click', event.x, event.y)
print(event.widget.find_closest(event.x, event.y))
lvl01 = tk.Toplevel(bd = 1, bg = 'black')
time.sleep(2)
print('2sec')
if __name__ == '__main__':
root = tk.Tk()
can = tk.Canvas(root, width = 400, height = 400)
can.pack()
x = 0
while x < 10:
x = x + 1
name = "object" + str(x)
print(name)
name = can.create_text(x * 30, x * 30, text = 'hello')
can.delete(object2)
Upvotes: 1
Views: 1905
Reputation: 704
You think you're binding a variable named object2 (or other number) to can.create_text.
What you're actually doing is first binding a variable called name to be a string 'object2', then you re-bind it to the return value of the can.create_text call.
There is more than one way to achieve the first result, but the one that springs to mind in this case that would allow quick access by name is to make a dict like so:
windows = {}
x = 0
while x < 10:
x = x + 1
name = "object" + str(x)
print(name)
windows[name] = can.create_text(x * 30, x * 30, text = 'hello')
can.delete(windows[object2])
Upvotes: 1
Reputation: 55499
You can't create variable names like that. This code:
name = "object" + str(x)
name = can.create_text(x * 30, x * 30, text = 'hello')
creates a string, binds it to the name name
, and then immediately overwrites it with the ID of the Canvas text object.
But you could store your Canvas text objects in a dictionary, using the name as the key.
import tkinter as tk
root = tk.Tk()
can = tk.Canvas(root, width = 400, height = 400)
can.pack()
objects = {}
for x in range(1, 11):
sx = str(x)
name = "object" + sx
print(name)
objects[name] = can.create_text(x * 30, x * 30, text = 'hello' + sx)
can.delete(objects["object2"])
root.mainloop()
Upvotes: 1