Reputation: 49
I am a newbie to python Tkinter.I have created a code which consists of a text box.I have additional File menu buttons : File,Open,Save,Exit Problem: I cant able to save the contents of my textfile even after saving,I can't able to open my file when I click over the Open button.
Coding:
from Tkinter import *
import tkMessageBox
import Tkinter
import Tkinter as tki
import tkFileDialog as th1
import tkFileDialog
class App(object):
def __init__(self,root):
Tkinter.Tk.__init__(self)
self.root = root
# create first Text label, widget and scrollbar
self.lbl1 = tki.Label(self, text="Type")
self.lbl1.grid(row=0,column=0,padx=2,pady=2)
self.txt1 = tki.Text(self, 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)
scrollb1 = tki.Scrollbar(txt_frm, command=self.txt1.yview)
scrollb1.grid(row=0, column=2, sticky='nsew')
self.txt1['yscrollcommand'] = scrollb1.set
def open_file():
f=(tkFileDialog.askopenfilename(
defaultextension = ".txt",
filetypes=[("All Types", ".*")]))
filename = f.name
return filename
def file_save():
f = th1.asksaveasfile(mode='w', defaultextension=".txt")
filename = f.name
return filename
def Exit():
exit()
root = tki.Tk()
menubar=Menu(root)
root.configure(menu=menubar)
filemenu=Menu(menubar,tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Save", command=file_save)
filemenu.add_command(label='Open', command = open_file)
filemenu.add_command(label='Exit', command = Exit)
app = App(root)
root.mainloop()
Please help me to fix my code!Answers will be appreciated!
Upvotes: 0
Views: 1304
Reputation: 369344
If you want to do file operation, use askopenfile
, asksaveasfile
instead.
from Tkinter import *
from tkFileDialog import askopenfile, asksaveasfile
class App(object):
def __init__(self, root):
self.lbl1 = Label(root, text="Type")
self.lbl1.pack(side=LEFT)
self.txt1 = Text(root, borderwidth=3, relief="sunken", height=4, width=55)
self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
self.txt1.pack(side=LEFT, expand=1, fill=BOTH)
scrollb1 = Scrollbar(root, command=self.txt1.yview)
scrollb1.pack(side=LEFT, fill=BOTH)
self.txt1['yscrollcommand'] = scrollb1.set
def open_file(self):
f = askopenfile(defaultextension=".txt", filetypes=[("All Types", ".*")])
if not f:
return
self.txt1.delete(1.0, END)
self.txt1.insert(END, f.read())
f.close()
def file_save(self):
f = asksaveasfile(mode='w', defaultextension=".txt")
if not f:
return
f.write(self.txt1.get(1.0, END))
f.close()
root = Tk()
app = App(root)
menubar = Menu(root)
root.configure(menu=menubar)
filemenu = Menu(menubar,tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Save", command=app.file_save)
filemenu.add_command(label='Open', command=app.open_file)
filemenu.add_command(label='Exit', command=root.quit)
root.mainloop()
Upvotes: 1