Как отменить запущенную функцию через условие variable = false в действии tkinter canvas - PullRequest
0 голосов
/ 22 февраля 2020

Я пытаюсь остановить хорошо работающую функцию рисования с помощью кнопки остановки. После нажатия кнопки запуска я могу вставить прямоугольники. Это то, что я хочу. Однако, если я активирую кнопку остановки (см. Код ниже), которая устанавливает условие для вставки = false, стиль может вставить прямоугольники. Такого не должно быть. Что не так?

import tkinter as tk

def insert_cells():
    global insert
    def xyposition(event):
        x = canvas.canvasx(event.x)
        y = canvas.canvasy(event.y)
        c = cell-1
        x0 = int((x//cell)*cell+1)
        y0 = int((y//cell)*cell+1)
        canvas.create_rectangle(x0,y0,x0+c,y0+c, width=0, fill='green')

    if not(insert):
        return
    else:
        canvas.bind("<Button-1>", xyposition)

def stop_insert_cells():
    global insert
    insert = False

# MAIN
root = tk.Tk()
root.geometry("400x400")
n=30
m=30
cell=10
w = n*cell
h = m*cell

# canvas
canvas = tk.Canvas(root,width = w, height = h, borderwidth = 0, highlightthickness=0)
canvas.place(x=20, y=20)

# border canvas
canvas.create_rectangle(0,0,w-1,h-1, outline = 'black')

# raster canvas
x1 = 1
y1 = 1
x2 = w-2
y2 = h-2
for i in range(1,m): # horizontal lines
    canvas.create_line(x1,i*cell,x2,i*cell)
for i in range(1,n): # vertical lines
    canvas.create_line(i*cell,y1,i*cell,y2)

# cell filling
insert = True

start_insert_button = tk.Button(root, text='start', command = insert_cells)
stop_insert_button = tk.Button(root, text = 'stop', command = stop_insert_cells)

stop_insert_button.pack(side='bottom')
start_insert_button.pack(side='bottom')

root.mainloop()

1 Ответ

0 голосов
/ 22 февраля 2020

Поскольку вы связали событие <Button-1> с обратным вызовом при нажатии кнопки start, но не отменяйте привязку обратного вызова при нажатии кнопки stop. Таким образом, обратный вызов в привязке будет по-прежнему вызываться при щелчке по холсту.

Либо вы отменяете обратный вызов (в этом случае не требуется глобальная переменная insert):

def insert_cells():
    def xyposition(event):
        x = canvas.canvasx(event.x)
        y = canvas.canvasy(event.y)
        c = cell-1
        x0 = int((x//cell)*cell+1)
        y0 = int((y//cell)*cell+1)
        canvas.create_rectangle(x0,y0,x0+c,y0+c, width=0, fill='green')

    canvas.bind("<Button-1>", xyposition)

def stop_insert_cells():
    canvas.unbind('<Button-1>')

или связать обратный вызов при запуске программы, а затем установить глобальную переменную insert для запуска или остановки вставки:

def xyposition(event):
    if insert:
        x = canvas.canvasx(event.x)
        y = canvas.canvasy(event.y)
        c = cell-1
        x0 = int((x//cell)*cell+1)
        y0 = int((y//cell)*cell+1)
        canvas.create_rectangle(x0,y0,x0+c,y0+c, width=0, fill='green')

def insert_cells():
    global insert
    insert = True

def stop_insert_cells():
    global insert
    insert = False

...

# cell filling
insert = False
canvas.bind('<Button-1>', xypostion)

Обратите внимание, что ваш код может создавать несколько прямоугольников в одной ячейке. Лучше сделать некоторую уборку, чтобы проверить, уже создан ли прямоугольник в ячейке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...