Python 7 Levels, L7, Unit 81, Simple Notepad I

Powered By EmbedPress

Exercise 1:

import tkinter as tk
from tkinter import filedialog

class Application:

    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Menu")
        self.root.geometry("300x300+100+100")
        self.filename = None
        self.createWidget()

    def createWidget(self):
        #create main menu and add to window
        self.menubar = tk.Menu(self.root)
        self.root["menu"] = self.menubar

        #create file\edit\help menu and add to main menu
        self.filemenu = tk.Menu(self.menubar)
        self.menubar.add_cascade(label="File",menu=self.filemenu)

        #add options in file menu
        self.filemenu.add_command(label="Open",command=self.openfile)
        self.filemenu.add_command(label="Save",command=self.savefile)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Quit")

        #create multi line text
        self.textpad = tk.Text(self.root,width=50,height=30)
        self.textpad.pack(fill="both")

        #create context menu
        self.contextMenu = tk.Menu(self.root)
        self.contextMenu.add_command(label="Cut")
        self.contextMenu.add_command(label="Copy")
        self.contextMenu.add_command(label="Paste")
        self.contextMenu.add_command(label="Choose Background Color")
        self.root.bind("<Button-3>",self.showContextMenu)

    def showContextMenu(self,event):
        self.contextMenu.post(event.x_root,event.y_root)


    def openfile(self):
        with tk.filedialog.askopenfile(title="Open Text File",initialdir="d:\file",\
                                  filetype=[("Text File",".txt")]) as file:
            self.textpad.insert(1.0,file.read())
            self.filename = file.name

    def savefile(self):
        with open(self.filename,"w") as file:
            c = self.textpad.get(1.0,"end")
            file.write(c)

    def exitfile(self):
        self.root.destroy()
            
    def run(self):
        self.root.mainloop()

app = Application()
app.run()

dahan1999

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts