Reputation: 3
I have a code to obtain input from the textbox and then write the input to a text file: Please help me to rectify my errors and my code from the following
My code:
import tkinter as tki
class App(object):
def __init__(self,root):
self.root = root
# create a Frame for the Text and Scrollbar
txt_frm = tki.Frame(self.root, width=600, height=400)
txt_frm.pack(fill="both", expand=True)
# ensure a consistent GUI size
txt_frm.grid_propagate(False)
self.txt1 = tki.Text(txt_frm, borderwidth=3, relief="sunken", height=4,width=55)
self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
self.txt1.grid(row=0, column=1, sticky="nsew", padx=2, pady=2)
button = tki.Button(self,text="Click", command = self.retrieve_input)
button.grid(column=2,row=0)
def retrieve_input(self):
input = self.txt1.get("0.0",'END-1c')
with open('text.txt','w') as f:
f.write(input)
f.close()
root = tki.Tk()
app = App(root)
root.mainloop()
errors:
File "C:/Python34/testtext.py", line 21, in <module>
app = App(root)
File "C:/Python34/testtext.py", line 13, in __init__
button = tki.Button(self,text="Click", command = self.retrieve_input)
File "C:\Python34\lib\tkinter\__init__.py", line 2156, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 2079, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Python34\lib\tkinter\__init__.py", line 2057, in _setup
self.tk = master.tk
AttributeError: 'App' object has no attribute 'tk'
Upvotes: 0
Views: 137
Reputation: 704
You have the parent of your button widget as self, which is a non tk object.
button = tki.Button(self...
If you tried to make self.root the parent, it will not work either as you have already packed your "txt_frm" onto it. (and you cannot mix packing and gridding under the same parent.
All you have to do is change the parent to txt_frm
button = tki.Button(txt_frm,text="Click", command = self.retrieve_input)
button.grid(column=2,row=0)
I would also recommend importing tkinter as tk, it is a little more standard.
Take a look at the traceback error, if the code is very linear and simple it should be all you need.
If you wanted to use the class instance self as an instance you would have to initialize the class under a tkinter class, below self is now a tkinter frame.
class App(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
def makeButton(self):
widget = tk.Button(self)
Upvotes: 2