单击提交按钮后自动关闭tk ENTRY窗口
我正在python 3.5中创建注销程序。我一直在环顾四周,看到如何使用“关闭/退出/退出”按钮关闭窗口。我想要做的就是在点击“提交”按钮后,自动关闭窗口,将输入框中的文本发送到文件。我试图以不同的方式在write_to_file中添加.destroy(),但我不断收到一个错误,说它没有定义。我为它创建了一个def,就像我看到的一些例子,但我不知道如何让write_to_file调用它。该程序将输入框中的内容正确写入文件。任何帮助,将不胜感激。单击提交按钮后自动关闭tk ENTRY窗口
class Writefiles:
def __init__(self):
win3 = Tk()
win3.title('Signature')
win3['bg'] = 'blue'
win3.geometry('300x200')
center(win3)
self.VarEnt = StringVar()
self.lab = Label(win3, text = "Name")
self.lab.grid(padx = 10, pady = 10)
self.ent = Entry(win3, textvariable = self.VarEnt, bd = 5, width = 45)
self.ent.focus()
self.ent.grid(padx = 10, pady = 10)
self.btn = Button(win3, text = 'Submit', width = 10, height = 2, background = 'gold', command = self.write_to_file)
self.btn.grid(padx = 10, pady = 10)
def write_to_file(self):
date = datetime.now().strftime(' %Y-%m-%d %H:%M:%S')
with open('sig.txt', 'a') as f:
f.write(self.ent.get() + date + '\n')
f.close()
def close_win(self): # close tkinter window
self.ent.destroy()
我需要做出WIN3全球,然后当我加入win3.destroy()到write_to_file所以点击按钮后会关闭窗口。如果你不使它成为全局的,你会得到一个NameError:'win3'没有被定义。
我删除了def close_win(self):section。
改正的代码:
class Writefiles:
def __init__(self):
self.win3 = Tk()
self.win3.title('Signature')
self.win3['bg'] = 'blue'
self.win3.geometry('300x200')
center(self.win3)
self.VarEnt = StringVar()
self.lab = Label(self.win3, text = "Name")
self.lab.grid(padx = 10, pady = 10)
self.ent = Entry(self.win3, textvariable = self.VarEnt, bd = 5, width = 45)
self.ent.focus()
self.ent.grid(padx = 10, pady = 10)
self.btn = Button(self.win3, text = 'Submit', width = 10, height = 2, background = 'gold', command = self.write_to_file)
self.btn.grid(padx = 10, pady = 10)
def write_to_file(self):
date = datetime.now().strftime(' %Y-%m-%d %H:%M:%S')
with open('sig.txt', 'a') as f:
f.write(self.ent.get() + date + '\n')
f.close()
self.win3.destroy() # to close window after files is written
编辑看到@gms评论之后,我删除了global
并添加self.
到WIN3条目。我编辑了上面的代码来显示更正。
你必须销毁win3窗口而不是条目。只需在def write_to_file(self)末尾写上 win3.destroy()即可。
您可以销毁窗口(如根窗口或作为根窗口孩子的Toplevel窗口),而不是窗口的窗口小部件。销毁根窗口会销毁所有窗口并退出程序。
在高清close_win(个体经营)你正试图摧毁耳鼻喉科项,而不是它的父窗口WIN3
当我将它添加到def的末尾时,出现NameError:'win3'未定义。我是否需要添加一些内容,以便在__init__部分查找它?我试图添加自我,但我然后得到一个AttributeError:'Writefiles'对象没有属性'win3'。 – poncanach
抱歉,延迟。我没有看到这个问题...... 您使用win3 = Tk(),并将其称为win3。您必须在类的定义中使用self.win3。所以将类中的所有win3改为self.win3。另外我不确定你是否需要全局win3 – gms
这两种方式都有效,但我现在明白使用'self'是python的方式,所以我将它添加到了班级中的所有win3中,并删除了全局。谢谢 – poncanach
关闭窗口确实是通过调用该窗口上的destroy()来完成的。如果你需要任何错误的帮助,你将不得不发布这些错误。 –