-2
我想在Tkinter中編寫一個Python GUI程序。我有基本的模板,但是當你點擊File > Open
時,我需要它來打開一個文件。Python Tk顯示和編輯文件
我該如何添加此功能?菜單欄和標籤已經在那裏。
#!/usr/bin/python
# -*- coding: utf-8 -*-
from ScrolledText import *
import tkFileDialog
import tkMessageBox
from Tkinter import Tk, Text, BOTH, W, N, E, S, Menu
from ttk import Frame, Button, Label, Style
def main():
root = Tk()
root.geometry("350x300+300+300")
app = Example(root)
root.mainloop()
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Grades")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
self.columnconfigure(1, weight=1)
self.columnconfigure(3, pad=7)
self.rowconfigure(3, weight=1)
self.rowconfigure(5, pad=7)
lbl = Label(self, text="Grades:")
lbl.grid(sticky=W, pady=4, padx=5)
lbl = Label(self, text="Average\n Grade:")
lbl.grid(row=3, column=3, pady=5)
textPad = ScrolledText(self)
textPad.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N)
abtn = Button(self, text="Save",command=save_command)
abtn.grid(row=1, column=3)
cbtn = Button(self, text="Close")
cbtn.grid(row=2, column=3, pady=4)
hbtn = Button(self, text="Help", command=about_command)
hbtn.grid(row=5, column=0, padx=5)
obtn = Button(self, text="OK")
obtn.grid(row=5, column=3)
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
submenu = Menu(fileMenu)
submenu.add_command(label="Student")
submenu.add_command(label="New Student")
fileMenu.add_cascade(label='Import', menu=submenu, underline=0)
fileMenu.add_command(label="Open...", command=open_command)
fileMenu.add_separator()
fileMenu.add_command(label="Exit", underline=0, command=self.onExit)
menubar.add_cascade(label="File", underline=0, menu=fileMenu)
def onExit(self):
self.quit()
def about_command():
label = tkMessageBox.showinfo("About", "Grade keeping\n program by Starwarsfan2099")
def save_command(self):
file = tkFileDialog.asksaveasfile(mode='w')
if file != None:
# slice off the last character from get, as an extra return is added
data = self.textPad.get('1.0', END+'-1c')
file.write(data)
file.close()
def open_command():
file = tkFileDialog.askopenfile(mode='rb',title='Select a file')
if file != None:
contents = file.read()
textPad.insert('1.0',contents)
file.close()
if __name__ == '__main__':
main()