Reputation: 83
In this code I am wondering how to get the rect
variable and use it in the Delete
method as I have tried to do. It currently comes up with an error.
from tkinter import *
def createRect(event):
rect = w.create_rectangle(50, 25, 150, 75, fill="blue")
return rect
def Start(event):
print("Single Clicked")
createRect(event)
def Delete(event):
i = createRect(event)
print("Double Clicked")
w.delete(i.rect)
root = Tk()
w = Canvas(root, width=200, height=100)
w.pack()
frame = Button(root, text="delete/make")
frame.bind("<Double-1>", Delete)
frame.bind("<Button-1>", Start)
frame.pack()
root.mainloop()
Upvotes: 0
Views: 79
Reputation: 402483
Generally, I would advise against using global variables since you have less control over who can modify them and how. But in this case, your Start
and Delete
functions are being called by the mainloop. You can create a container object and use this in your methods.
class MyRect:
def __init__(self):
self.rect = None
self.isSet = False
Then, inside your tkinter code, you can use it like this:
myrect = MyRect()
def Start(event):
if not myrect.isSet:
print("Single Clicked")
myrect.rect = createRect(event)
myrect.isSet = True
def Delete(event):
if myrect.isSet:
print("Double Clicked")
w.delete(myrect.rect)
myrect.rect = None
myrect.isSet = False
You can also handle users double clicking or clicking button 1 more times than they should this way.
If you're feeling adventurous, you could add __setattr__
and __getattr__
methods that'll control what happens when you modify rect instances when you shouldn't.
Upvotes: 1