Writing to the kom_kv1
variable inside the function creates a new local variable and does not change the value of the global variable named kom_kv1
outside the function. If you need to write from a function to a global variable, you must explicitly indicate that you want to use a global variable:
def addFlat(): global kom_kv1 kom_kv1=Entry(root) kom_kv1.grid()
If you need the ability to consistently delete added items, you need to remember them all, and not just one. And still it is necessary to agree, we delete since the oldest or from the newest ( FIFO or LIFO ).
Suppose this is a FIFO (i.e. a queue — the first one added will be deleted first). We use the usual list as storage.
from tkinter import * root=Tk() root.title("Нумерация") flats = [] counter = 1 def addFlat(): global counter kom_kv = Entry(root) kom_kv.grid() # Для наглядности в текстовое поле записываем его номер по порядку: kom_kv.insert(0, str(counter)) counter += 1 flats.append(kom_kv) def deleteFlat(): if flats: # Если список не пустой # Достаем из начала списка один элемент, и сразу удаляем из окна flats.pop(0).grid_forget() # Если нужно удалять начиная с последнего добавленного, то меняем на такую строку: # flats.pop().grid_forget() plus=Button(root,text='Добавить квартиру', command=addFlat) plus.grid() plus2=Button(root,text='Удалить квартиру', command=deleteFlat) plus2.grid() root.mainloop()
By the way, for deletion, it is better to use not grid_forget
, but destroy
; otherwise, all "remote" controls will remain in memory, although they will not be displayed on the screen. grid_forget
needed to temporarily hide an element so that it can be displayed again using the grid
method.