清除tkinter条目小部件中的文本

时间:2014-08-12 20:17:57

标签: 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()

我尝试使用我想要删除的变量列表创建fields(如上所述)并在函数delete_entries()中迭代它,但是这会返回错误,因为字段中的条目是字符串。我尝试用fields = ExperimentNumber替换字段,但这会返回错误,因为尚未定义ExperimentNumber。最后,我尝试将ExperimentNumber放在删除函数中,即

def delete_entries():
      ExperimentNumber.delete(0,End)

但这不起作用,因为ExperimentNumber具有属性NoneType(我不明白为什么会这样,因为delete_entries()功能不是{\ n}在通过函数ExperimentNumber创建UserInput Entry小部件之后调用。如何删除Entry小部件中的所有文本?我在实际代码中有大约20个,并希望用户只需按一下按钮即可清除所有字段。

1 个答案:

答案 0 :(得分:4)

你走在正确的轨道上,但你错过了两件小事。我在你的代码中添加了这两个,并尝试用注释进行解释。

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()