我是python Tkinter的新手。我创建了一个由文本框组成的代码。我有其他文件菜单按钮:文件,打开,保存,退出 问题:即使保存后我也无法保存文本文件的内容,单击“打开”按钮时无法打开文件。
编码:
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()
请帮我修改我的代码!我将不胜感激!
答案 0 :(得分:1)
如果您想进行文件操作,请改用askopenfile
,asksaveasfile
。
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()