E
E
Eugene2019-12-29 13:20:31
Python
Eugene, 2019-12-29 13:20:31

How to delete objects in canvas python?

The task is as follows: numbers are generated in different places on the screen. When you click on them, they should disappear.

canv.create_text(x1, y1, anchor=W, font=("Purisa", size),
                text = 1, tag=1)
canv.create_text(x1, y1, anchor=W, font=("Purisa", size),
                text = 2, tag=2)
canv.create_text(x1, y1, anchor=W, font=("Purisa", size),
                text = 3, tag=3)
canv.tag_bind(???, '<Button-1>', click)

How to form multiple bandages? And how then to understand which number was clicked and delete it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SuckMyPython, 2020-01-06
@SuckMyPython

Ready!

# -*- coding: utf8 -*-
from tkinter import*
import tkinter.ttk as ttk

root = Tk()

canv = Canvas(root, width=120, height=50)
canv.pack()

def click1(self):
  canv.delete(z1)

def click2(self):
  canv.delete(z2)

def click3(self):
  canv.delete(z3)
  
z1 = canv.create_text(20, 20, anchor=W, font=("Purisa", 20), text = 1, tag=1)
z2 = canv.create_text(50, 20, anchor=W, font=("Purisa", 20), text = 2, tag=2)
z3 = canv.create_text(80, 20, anchor=W, font=("Purisa", 20), text = 3, tag=3)

canv.tag_bind(z1, '<Button-1>', click1)
canv.tag_bind(z2, '<Button-1>', click2)
canv.tag_bind(z3, '<Button-1>', click3)

root.mainloop()

But, if you need something like a random-based game, then here it is:
# -*- coding: utf8 -*-
from tkinter import*
import tkinter.ttk as ttk
import random

root = Tk()
root.geometry("500x500")

def z0():
  btn.destroy()
  canv = Canvas(root, width=500, height=500)
  canv.pack()

  def click(self):
    global rin		
    global num
    canv.delete(num)

    dbrin = rin
    print(dbrin)

    z1()
    
  def z1():
    global rin
    global num
    rin = random.SystemRandom().choice(["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"])
    xy = random.SystemRandom().choice(["50", "100", "150", "200", "250", "300", "350", "400", "450"])
    yx = random.SystemRandom().choice(["450", "400", "350", "300", "250", "200", "150", "100", "50"])

    x1 = xy
    y1 = yx
    
    num = canv.create_text(x1, y1, anchor=W, font=("Purisa", 20), text = rin)
    canv.tag_bind(num, '<Button-1>', click)

  z1()

btn = Button(root, text="START", width=10, height=5, fg="black", command=z0)
btn.pack()

root.mainloop()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question