Tkinter创建清除按钮以清除各种文本框



我有大约40个从d1到d40命名的文本框。

目前,我已经创建了一个有40行的Clear Button,每行都说明文本框编号(例如:"d1.delete(0,END("(;以清除文本框(。

我知道应该有更聪明的方法。。。但我试了很多次都失败了。

下面请找到我的代码摘录:

import tkinter as tk
from tkinter import *

win = Tk()
win.wm_title("Testing")
win.wm_geometry("400x400+10+30")
v = StringVar()
v.set('abcd')
d1 = Entry(win, text=v)
d1.place(x=10, y=10, height=30, width=400)
s = StringVar()
s.set('abc22222222')
d2 = Entry(win, text=s)  
d2.place(x=10, y=50, height=30, width=400)
t = StringVar()
t.set('abc22sdfefe222222')
d3 = Entry(win, text=t)  
d3.place(x=10, y=90, height=30, width=400)
def clearcomm():
n = 0
for i in range(3):
n +=1
'd{}.delete(0, END)'.format(n)
Button(win, text='Clear', command=clearcomm, height=1, width=6, font=("arial", 7, "bold"), fg="white", bg="red").place(x=10, y=150)        

mainloop()

然后我也尝试了:

clearlist = []
n = 0
for i in range(3):
n +=1
command = 'd{}.delete(0, END)'.format(n)
clearlist.append(command)

n = 0
def clearcomm():
for list in clearlist:
return

但这一次没有回应。。。所以我不知道该怎么做。如果你能给我一些建议,我将不胜感激。

您可能会更聪明地查找要清除的所有文本框的列表:

global textboxes
textboxes = []
global contents
contents = []
for y in [10,50,90]:
v = StringVar()
v.set('sometext')
d1 = Entry(win, textvariable=v)
d1.place(x=10, y=y, height=30, width=400)
textboxes.append(d1)
contents.append(v)

然后你有两个列表。一个包含所有入口小部件,另一个包含全部内容。您可以使用for循环来遍历所有对象:

def clearcomm():
for c in contents:
c.set('')

def clearcomm():
for t in textboxes:
t.delete(0,END)

由于您使用了文本变量,所以两者都应该起作用。

[编辑:全球声明统一发布。感谢注意,酷云。]

最新更新