Advertisement
sphinx2001

Очистка tkinter canvas

Nov 29th, 2020
808
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. from tkinter import *
  2. from tkinter import messagebox
  3. import time
  4. import random
  5.  
  6. tk = Tk()
  7. app_running = True
  8. size_canvas_x = 700
  9. size_canvas_y = 500
  10. menu_x = 250
  11. menu_y = 50
  12. canvas_elements = []
  13.  
  14.  
  15. def click_canvas(event):
  16.     mouse_x = canvas.winfo_pointerx() - canvas.winfo_rootx()
  17.     mouse_y = canvas.winfo_pointery() - canvas.winfo_rooty()
  18.     if 0 <= mouse_x <= size_canvas_x and 0 <= mouse_y <= size_canvas_y:
  19.         x = mouse_x
  20.         y = mouse_y
  21.         rgb_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
  22.         canvas_elements.append(canvas.create_rectangle(x, y, x + 50, y + 50, fill=_from_rgb(rgb_color)))
  23.  
  24.  
  25. def _from_rgb(rgb):
  26.     """translates an rgb tuple of int to a tkinter friendly color code
  27.    """
  28.     return "#%02x%02x%02x" % rgb
  29.  
  30.  
  31. def test_canvas_clear():
  32.     if canvas_elements:
  33.         cid = canvas_elements.pop()
  34.         canvas.delete(cid)
  35.  
  36.  
  37. def test_canvas():
  38.     x = random.randint(0, size_canvas_x)
  39.     y = random.randint(0, size_canvas_y)
  40.     rgb_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
  41.     canvas_elements.append(canvas.create_rectangle(x, y, x+50, y+50, fill=_from_rgb(rgb_color)))
  42.  
  43.  
  44. def on_closing():
  45.     global app_running
  46.     if messagebox.askokcancel("Выход из игры", "Хотите выйти из игры?"):
  47.         app_running = False
  48.         tk.destroy()
  49.  
  50.  
  51. tk.protocol("WM_DELETE_WINDOW", on_closing)
  52. tk.title("Test")
  53. tk.resizable(0, 0)
  54. tk.wm_attributes("-topmost", 1)
  55. canvas = Canvas(tk, width=size_canvas_x + menu_x, height=size_canvas_y + menu_y, bd=0,
  56.                 highlightthickness=0)
  57. canvas.create_rectangle(0, 0, size_canvas_x, size_canvas_y, fill="white")
  58. canvas.pack()
  59. tk.update()
  60.  
  61. button1 = Button(text="Test", command=test_canvas)
  62. button1.place(x=size_canvas_x+10, y=20, width=230, height=50)
  63.  
  64. button2 = Button(text="Clear", command=test_canvas_clear)
  65. button2.place(x=size_canvas_x+10, y=90, width=230, height=50)
  66.  
  67. canvas.bind_all("<Button-1>", click_canvas)  # ЛКМ
  68. canvas.bind_all("<Button-3>", click_canvas)  # ПКМ
  69.  
  70. while app_running:
  71.     if app_running:
  72.         tk.update_idletasks()
  73.         tk.update()
  74.     time.sleep(0.005)
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement