-2

When the window is open, I keep adding element to my list. I want to close the tkinter window automatically when my list length exceeds certain number, I couldn't get any good answer on internet.

Answers from How do I close a tkinter window? mostly close the tkinter window using button which is not the way I want.

I tried this code but it doesn't work

root = Tk()
#Some code....

#function to be called when mouse is clicked
def insertcoords(event):
    #outputting x and y coords to console
    coord.append([event.x, event.y])

#mouseclick event
canvas.bind("<Button 1>",insertcoords)

if len(coord) > 4 : #coord is my list
    root.destroy()
root.mainloop() 
gameon67
  • 3,981
  • 5
  • 35
  • 61
  • 1. How are you adding elements to list? 2. When to check for `len(coord) > 4` after adding all elements? or each time after adding an element? – Partho63 Feb 18 '19 at 08:51
  • @Partho63 updated my post. I prefer check every time i add element – gameon67 Feb 18 '19 at 08:59
  • 1
    Just move the if block into `insertcoords()`. – acw1668 Feb 18 '19 at 09:00
  • 1
    Your check of len() only happens once; you need to place the check in some event, or loop, that repeats to check it more than once. – Andy G Feb 18 '19 at 09:00
  • @AndyG @acw1668 Thank you, it's my first time using tkinter so a little bit confuse how the `root.mainlopp` works – gameon67 Feb 18 '19 at 23:58

1 Answers1

2

You have to put

if len(coord) > 4 :
    root.destroy()

inside your insertcoords() function. Check the following example:

from tkinter import *

root = Tk()

added_elements = []

def CheckLength():
    listbox.insert(END, entry_value.get())
    added_elements.append(entry_value.get())
    if len(added_elements) > 4:
        root.destroy()

entry_value = StringVar()
entry = Entry(root, textvariable=entry_value)
entry.grid(row=0, column=0)

button = Button(root, text="Add", command=CheckLength)
button.grid(row=0, column=1)

listbox = Listbox(root)
listbox.grid(row=1, column=0, columnspan=2)

root.mainloop()

Here is updated version of your code:

from tkinter import *

root = Tk()

coord = []

def insertcoords(event):
    coord.append([event.x, event.y])
    print(event.x, event.y)
    if len(coord) > 4:
        root.destroy()

canvas = Canvas(root)
canvas.grid(row=0, column=0)
canvas.bind("<Button 1>", insertcoords)

root.mainloop()
Partho63
  • 3,117
  • 2
  • 21
  • 39
  • 1
    Thank you, it's my first time using tkinter so a little bit confuse how the `root.mainlopp` works – gameon67 Feb 18 '19 at 23:59