Reputation: 892
In tkinter, python, I'm trying to create a program which involves creating a shape onto a canvas and with a button click, and cause no more shapes to be created. Here's my code:
from tkinter import *
root = Tk()
canvas = Canvas(root) # Creating Canvas
canvas.pack()
def create(event):
x1, y1 = (event.x - 5), (event.y - 5)
x2, y2 = (event.x + 5), (event.y + 5) # Creates Rectangle Where Button Clicked
canvas.create_rectangle(x1,y1,x2,y2,fill='red')
root.bind_all("<Button-1>", create) # Binds Mouse Click Button
citybg = PhotoImage(file= r"example.png")
citybgimage = canvas.create_image(50, 50, image=citybg) # Background for Canvas
My question is how to make the rectangle only create able once and once only, and the create
function can no longer be executed. Hope this was explained well, and I hope it can be answered well.
Upvotes: 0
Views: 1496
Reputation: 2676
I think you can unbind the function after finish running the function. Like this:
def create(event):
x1, y1 = (event.x - 5), (event.y - 5)
x2, y2 = (event.x + 5), (event.y + 5) # Creates Rectangle Where Button Clicked
canvas.create_rectangle(x1,y1,x2,y2,fill='red')
root.unbind_all('<Button-1>') #You can later bind <Button-1> to other functions as well
Upvotes: 0
Reputation: 565
Well, a simple solution (but not that pretty) will be to add a Boolean flag that will be set as True when the function run for the first time. Then use if statement and return and not do anything in create if True.
something like this (createRan - is that Boolean flag):
root = Tk()
canvas = Canvas(root) # Creating Canvas
canvas.pack()
createRan = False
def create(event):
if(createRan):
return
else:
createRan=True
x1, y1 = (event.x - 5), (event.y - 5)
x2, y2 = (event.x + 5), (event.y + 5) # Creates Rectangle Where Button Clicked
canvas.create_rectangle(x1,y1,x2,y2,fill='red')
Upvotes: 2
Reputation: 161
Use a boolean to check whether the rectangle has already been created or not, like that :
rectangleCreated = False
def create(event):
if rectangleCreated:
return
x1, y1 = (event.x - 5), (event.y - 5)
x2, y2 = (event.x + 5), (event.y + 5)
canvas.create_rectangle(x1,y1,x2,y2,fill='red')
rectangleCreated = True
Upvotes: 3