Python 列表长度超过一定数量后,如何自动关闭tkinter窗口?
当窗口打开时,我不断地向列表中添加元素。当我的列表长度超过某个数字时,我想自动关闭tkinter窗口,但我在互联网上找不到任何好的答案 答案大多是用按钮关闭tkinter窗口,这不是我想要的方式 我试过这个代码,但不起作用Python 列表长度超过一定数量后,如何自动关闭tkinter窗口?,python,tkinter,Python,Tkinter,当窗口打开时,我不断地向列表中添加元素。当我的列表长度超过某个数字时,我想自动关闭tkinter窗口,但我在互联网上找不到任何好的答案 答案大多是用按钮关闭tkinter窗口,这不是我想要的方式 我试过这个代码,但不起作用 root = Tk() #Some code.... #function to be called when mouse is clicked def insertcoords(event): #outputting x and y coords to consol
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()
root=Tk()
#一些代码。。。。
#单击鼠标时要调用的函数
def insertcoords(事件):
#将x和y坐标输出到控制台
坐标追加([event.x,event.y])
#鼠标点击事件
canvas.bind(“,insertcoords)
如果len(coord)>4:#coord是我的列表
root.destroy()
root.mainloop()
您必须将
if len(coord) > 4 :
root.destroy()
在insertcoords()函数中。检查以下示例:
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()
以下是您的代码的更新版本:
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()
从tkinter导入*
root=Tk()
coord=[]
def insertcoords(事件):
坐标追加([event.x,event.y])
打印(事件x、事件y)
如果len(coord)>4:
root.destroy()
画布=画布(根)
canvas.grid(行=0,列=0)
canvas.bind(“,insertcoords)
root.mainloop()
1。如何将元素添加到列表中?2.添加所有元素后,何时检查len(coord)>4
?还是每次添加元素后?@Partho63都会更新我的帖子。我更喜欢每次添加元素时都检查只需将if块移动到insertcoords()
。您对len()的检查只发生一次;您需要将检查放在某个重复检查多次的事件或循环中。@AndyG@acw1668谢谢,这是我第一次使用tkinter,所以有点混淆了root.mainlopp
的工作原理谢谢,这是我第一次使用tkinter,所以有点混淆了root.mainlopp
的工作原理