218*_*218 2 python user-interface tkinter
我正在使用 Tkinter 条目小部件来允许用户将文本输入到 GUI。条目小部件具有默认文本,我想通过按一下按钮清除它们。我有以下代码:
from Tkinter import *
def delete_entries(fields):
for field in fields:
field.delete(0,END)
def UserInput(status,name):
optionFrame = Frame(root)
optionLabel = Label(optionFrame)
optionLabel["text"] = name
optionLabel.pack(side=LEFT)
var = StringVar(root)
var.set(status)
w = Entry(optionFrame, textvariable= var)
w.pack(side = LEFT)
optionFrame.pack()
if __name__ == '__main__':
root = Tk()
fields = 'ExperimentNumber', 'OutputFileName', 'npts1', 'block1'
ExperimentNumber = UserInput("1", "Experiment number")
OutputFileName = UserInput("output.txt", "Output file name")
npts1 = UserInput("1000", "Number of points")
block1 = UserInput("8", "Block size")
Delete_button = Button(root, text = 'Clear all', command = delete_entries(fields))
Delete_button.pack()
Run Code Online (Sandbox Code Playgroud)
我尝试fields
使用要删除的变量列表(如上)创建并在函数中迭代它delete_entries()
,但是这会返回错误,因为字段中的条目是字符串。我曾尝试用fields = ExperimentNumber
例如替换字段,但这会返回错误,因为还没有定义 ExperimentNumber。最后我尝试放入ExperimentNumber
删除功能即
def delete_entries():
ExperimentNumber.delete(0,End)
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为ExperimentNumber
有属性NoneType
(我不明白为什么会这样,因为delete_entries()
直到ExperimentNumber
通过函数创建 Entry 小部件之后才会调用该函数UserInput
)。如何删除 Entry 小部件中的所有文本?我的实际代码中有大约 20 个这样的内容,并且希望用户能够一键清除所有字段。
你在正确的轨道上,但你错过了两件小事。我在您的代码中添加了这两个并尝试用注释进行解释。
from Tkinter import *
def delete_entries():
for field in fields:
field.delete(0,END)
def UserInput(status,name):
optionFrame = Frame(root)
optionLabel = Label(optionFrame)
optionLabel["text"] = name
optionLabel.pack(side=LEFT)
var = StringVar(root)
var.set(status)
w = Entry(optionFrame, textvariable= var)
w.pack(side = LEFT)
optionFrame.pack()
return w
#this return is crucial because if you don't return your widget's identity,
#you can not use them in another function
if __name__ == '__main__':
root = Tk()
ExperimentNumber = UserInput("1", "Experiment number")
OutputFileName = UserInput("output.txt", "Output file name")
npts1 = UserInput("1000", "Number of points")
block1 = UserInput("8", "Block size")
#you are saying it does not work because of they are strings.
#then don't assign strings to fields. assign variables.
fields = ExperimentNumber, OutputFileName, npts1, block1
#since fields is defined in global scope, you don't need to use it as parameter
Delete_button = Button(root, text = 'Clear all', command = delete_entries)
Delete_button.pack()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)