I have the following program using Tkinter in Python. it works well in its simple format but gives me errors when I try converting it to a class approach. I'm tracking a previous Tkinter GUI session by storing entered values in a text file and creating a handler to track the end of the session. WHen a new session is opened, the entry value from the previous session is already displayed in the entry box
#!usr/bin/env python
from Tkinter import *
# Define input retrieve function for application input
def retrieve_text():
print(app_entry.get())
def handler():
f = open("backup.txt", "w")
f.write(app_entry.get())
f.close()
app_win.destroy()
if __name__ == "__main__":
# Create window (or form)
app_win = Tk()
# Create label
app_label = Label(app_win, text="Enter value")
app_label.pack()
# Create entry box
t = open("backup.txt")
var1 = t.readlines()
Text = StringVar()
Text.set(var1[0])
app_entry = Entry(app_win,textvariable=Text)
app_entry.pack()
# Create button
app_button = Button(app_win, text="Print Value", command=app_win.retrieve_text)
app_button.pack()
app_win.protocol("WM_DELETE_WINDOW", handler)
# Initialize GUI loop
app_win.mainloop()
When I try to convert to a class based approach, I get an error "MyGUI instance has no attribute named protocol". My class structure is as follows:
#!usr/bin/env python
from Tkinter import *
class Tracker(Frame):
def __init__(self):
Frame.__init__(self)
# Create label
app_label = Label(self, text="Enter value")
app_label.pack()
# Create entry box
t = open("backup.txt")
var1 = t.readlines()
Text = StringVar()
Text.set(var1[0])
app_entry = Entry(self,textvariable=Text)
app_entry.pack()
# Create button
app_button = Button(self, text="Print Value", command=self.retrieve_text)
app_button.pack()
self.entry1 = app_entry.get()
self.protocol("WM_DELETE_WINDOW", self.handler)
def retrieve_text():
print(self.entry1)
def handler():
f = open("backup.txt", "w")
f.write(self.entry1)
f.close()
self.destroy()
if __name__ == "__main__":
# Create window (or form)
app = Tracker()
# Initialize GUI loop
app.mainloop()
Could anyone tell me what I'm doing wrong? Is the location where I'm specifying my "WM_DELETE_WINDOW" correct?