iT邦幫忙

2021 iThome 鐵人賽

DAY 26
1
自我挑戰組

一起用python寫UI系列 第 26

Day26 用python寫UI-聊聊Text(三)

今天的程式碼也超長的,因為範例有結合昨天的一起呈現,所以就越加越長了~

♠♣今天的文章大綱♥♦

  • 儲存
  • 開啟新檔
  • 開啟舊檔
  • 插入影像

儲存

import tkinter as tk
from tkinter.filedialog import asksaveasfile

root = tk.Tk()
root.configure(bg="#7AFEC6")
root.title("filename")
root.iconbitmap('heart_green.ico')
root.geometry('300x100')

def cut():
    text.event_generate("<<Cut>>")

def copy():
    text.event_generate("<<Copy>>")

def paste():
    text.event_generate("<<Paste>>")

def showPopupMenu(event):
    popupmenu.post(event.x_root,event.y_root)

def undo():
    try:
        text.edit_undo()
    except:
        print("No action")

def redo():
    try:
        text.edit_redo()
    except:
        print("No action")

def spelling():
    text.tag_remove("Error","1.0","end")
    textwords=text.get("1.0","end").split()
    print("Dictionary")

    startChar=("(")
    endChar=(".",",","?",")","!",":",";")

    start="1.0"
    for word in textwords:
        if word[0] in startChar:
            word=word[1:]
        if word[-1] in startChar:
            word=word[:-1]
        if (word not in dicts and word.lower()not in dicts):
            print("error",word)
            pos=text.search(word,start,"end")
            text.tag_add("spellErr",pos,"%s+%dc" % (pos,len(word)))
            pos="%s+%dc" % (pos,len(word))

def clr():
    text.tag_remove("spellErr","1.0","end")

def save():                 #資料儲存開始
    global filename
    textC=text.get("1.0","end")
    filename=tk.filedialog.asksaveasfile()
    if filename == "":
        output.write(textC)
        root.title(filename)
        
filename="filename"
menubar=tk.Menu(root)
fM=tk.Menu(menubar,tearoff=False)
menubar.add_cascade(label="File",menu=fM)
fM.add_command(label="Save as",command=save)
fM.add_separator()
fM.add_command(label="Exit",command=root.destroy)
root.config(menu=menubar)

popupmenu=tk.Menu(root,tearoff=False)
popupmenu.add_command(label="cut",command=cut)
popupmenu.add_command(label="copy",command=copy)
popupmenu.add_command(label="paste",command=paste)

root.bind("<Button-3>",showPopupMenu)

toolbar=tk.Frame(root,relief="raised",borderwidth=1)
toolbar.pack(side="top",fill="x",padx=2,pady=1)

chkBtn=tk.Button(toolbar,text="check",command=spelling)
chkBtn.pack(side="left", pady=2)
clrBtn=tk.Button(toolbar,text="clear",command=clr)
clrBtn.pack(side="left", pady=2)
undoBtn = tk.Button(toolbar, text="Undo", command=undo)
undoBtn.pack(side="left", pady=2)
redoBtn = tk.Button (toolbar, text="Redo", command=redo)
redoBtn.pack(side="left", pady=2)

text = tk.Text (root, undo=True)
text.pack(fill="both", expand=True, padx=3, pady=2)
text.insert ('end', "我沒有說謊 我何必說謊\n")
text.insert ('end', "妳懂我的 我對妳從來就不會假裝 \n")
text.insert ('end', "我哪有說謊\n")
text.insert ('end', "請別以為妳有多難忘 笑是真的不是我逞強\n")

text.tag_configure("spellerror",foreground="red")
with open("my.Dict.txt","r") as dictObj:
    dicts=dictObj.read().split("\n")

root.mainloop()

執行結果⬇⬇⬇
https://ithelp.ithome.com.tw/upload/images/20211010/201400475yOrRUWbh8.png
選擇儲存後⬇⬇⬇
https://ithelp.ithome.com.tw/upload/images/20211010/20140047w28U9FpvZU.png


開啟新檔

import tkinter as tk
from tkinter.filedialog import asksaveasfile

root = tk.Tk()
root.configure(bg="#7AFEC6")
root.title('cuteluluWindow')
root.iconbitmap('heart_green.ico')
root.geometry('300x100')

def cut():
    text.event_generate("<<Cut>>")

def copy():
    text.event_generate("<<Copy>>")

def paste():
    text.event_generate("<<Paste>>")

def showPopupMenu(event):
    popupmenu.post(event.x_root,event.y_root)

def undo():
    try:
        text.edit_undo()
    except:
        print("No action")

def redo():
    try:
        text.edit_redo()
    except:
        print("No action")

def spelling():
    text.tag_remove("Error","1.0","end")
    textwords=text.get("1.0","end").split()
    print("Dictionary")

    startChar=("(")
    endChar=(".",",","?",")","!",":",";")

    start="1.0"
    for word in textwords:
        if word[0] in startChar:
            word=word[1:]
        if word[-1] in startChar:
            word=word[:-1]
        if (word not in dicts and word.lower()not in dicts):
            print("error",word)
            pos=text.search(word,start,"end")
            text.tag_add("spellErr",pos,"%s+%dc" % (pos,len(word)))
            pos="%s+%dc" % (pos,len(word))

def clr():
    text.tag_remove("spellErr","1.0","end")

def save():                 
    global filename
    textC=text.get("1.0","end")
    filename=tk.filedialog.asksaveasfile()
    if filename == "":
        output.write(textC)
        

def new():               #開新資料夾開始
    text.delete("1.0","end")
    

menubar=tk.Menu(root)
fM=tk.Menu(menubar,tearoff=False)
menubar.add_cascade(label="File",menu=fM)
fM.add_command(label="Save as",command=save)
fM.add_command(label="New File",command=new)
fM.add_separator()
fM.add_command(label="Exit",command=root.destroy)
root.config(menu=menubar)

popupmenu=tk.Menu(root,tearoff=False)
popupmenu.add_command(label="cut",command=cut)
popupmenu.add_command(label="copy",command=copy)
popupmenu.add_command(label="paste",command=paste)

root.bind("<Button-3>",showPopupMenu)

toolbar=tk.Frame(root,relief="raised",borderwidth=1)
toolbar.pack(side="top",fill="x",padx=2,pady=1)

chkBtn=tk.Button(toolbar,text="check",command=spelling)
chkBtn.pack(side="left", pady=2)
clrBtn=tk.Button(toolbar,text="clear",command=clr)
clrBtn.pack(side="left", pady=2)
undoBtn = tk.Button(toolbar, text="Undo", command=undo)
undoBtn.pack(side="left", pady=2)
redoBtn = tk.Button (toolbar, text="Redo", command=redo)
redoBtn.pack(side="left", pady=2)

text = tk.Text (root, undo=True)
text.pack(fill="both", expand=True, padx=3, pady=2)
text.insert ('end', "我沒有說謊 我何必說謊\n")
text.insert ('end', "妳懂我的 我對妳從來就不會假裝 \n")
text.insert ('end', "我哪有說謊\n")
text.insert ('end', "請別以為妳有多難忘 笑是真的不是我逞強\n")

text.tag_configure("spellerror",foreground="red")
with open("my.Dict.txt","r") as dictObj:
    dicts=dictObj.read().split("\n")

root.mainloop()

執行結果⬇⬇⬇
https://ithelp.ithome.com.tw/upload/images/20211010/20140047jFR8w5ZOQA.png
選擇開啟新檔後⬇⬇⬇
https://ithelp.ithome.com.tw/upload/images/20211010/201400476Tj1Exvo84.png


開啟舊檔

import tkinter as tk
from tkinter.filedialog import asksaveasfile
from tkinter.filedialog import askopenfile

root = tk.Tk()
root.configure(bg="#7AFEC6")
root.title('cuteluluWindow')
root.iconbitmap('heart_green.ico')
root.geometry('300x100')

def cut():
    text.event_generate("<<Cut>>")

def copy():
    text.event_generate("<<Copy>>")

def paste():
    text.event_generate("<<Paste>>")

def showPopupMenu(event):
    popupmenu.post(event.x_root,event.y_root)

def undo():
    try:
        text.edit_undo()
    except:
        print("No action")

def redo():
    try:
        text.edit_redo()
    except:
        print("No action")

def spelling():
    text.tag_remove("Error","1.0","end")
    textwords=text.get("1.0","end").split()
    print("Dictionary")

    startChar=("(")
    endChar=(".",",","?",")","!",":",";")

    start="1.0"
    for word in textwords:
        if word[0] in startChar:
            word=word[1:]
        if word[-1] in startChar:
            word=word[:-1]
        if (word not in dicts and word.lower()not in dicts):
            print("error",word)
            pos=text.search(word,start,"end")
            text.tag_add("spellErr",pos,"%s+%dc" % (pos,len(word)))
            pos="%s+%dc" % (pos,len(word))

def clr():
    text.tag_remove("spellErr","1.0","end")

def save():                 
    global filename
    textC=text.get("1.0","end")
    filename=tk.filedialog.asksaveasfile(defaul=".txt")
    if filename == "":
        return
    with open(filename,"write")as out:
        out.write(textC)        

def new():               
    text.delete("1.0","end")

def openf():          #開舊資料夾開始
    global filename
    filename=tk.filedialog.askopenfile()
    if filename == "":
        return
    with open(filename,"read")as file:
        read=file.read()
        text.delete("1.0","end")
        text.insert(read,"end")


menubar=tk.Menu(root)
fM=tk.Menu(menubar,tearoff=False)
menubar.add_cascade(label="File",menu=fM)
fM.add_command(label="Save as",command=save)
fM.add_command(label="Open File",command=openf)
fM.add_command(label="New File",command=new)
fM.add_separator()
fM.add_command(label="Exit",command=root.destroy)
root.config(menu=menubar)

popupmenu=tk.Menu(root,tearoff=False)
popupmenu.add_command(label="cut",command=cut)
popupmenu.add_command(label="copy",command=copy)
popupmenu.add_command(label="paste",command=paste)

root.bind("<Button-3>",showPopupMenu)

toolbar=tk.Frame(root,relief="raised",borderwidth=1)
toolbar.pack(side="top",fill="x",padx=2,pady=1)

chkBtn=tk.Button(toolbar,text="check",command=spelling)
chkBtn.pack(side="left", pady=2)
clrBtn=tk.Button(toolbar,text="clear",command=clr)
clrBtn.pack(side="left", pady=2)
undoBtn = tk.Button(toolbar, text="Undo", command=undo)
undoBtn.pack(side="left", pady=2)
redoBtn = tk.Button (toolbar, text="Redo", command=redo)
redoBtn.pack(side="left", pady=2)

text = tk.Text (root, undo=True)
text.pack(fill="both", expand=True, padx=3, pady=2)
text.insert ('end', "我沒有說謊 我何必說謊\n")
text.insert ('end', "妳懂我的 我對妳從來就不會假裝 \n")
text.insert ('end', "我哪有說謊\n")
text.insert ('end', "請別以為妳有多難忘 笑是真的不是我逞強\n")

text.tag_configure("spellerror",foreground="red")
with open("my.Dict.txt","r") as dictObj:
    dicts=dictObj.read().split("\n")

root.mainloop()

執行結果⬇⬇⬇
https://ithelp.ithome.com.tw/upload/images/20211010/201400474fCZBQ0HOQ.png
選擇開啟舊檔後⬇⬇⬇
https://ithelp.ithome.com.tw/upload/images/20211010/20140047DSnEIwsWHR.png


插入影像

插入影像很簡單,就是用insert就可以了。

import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
root.configure(bg="#7AFEC6")
root.title('cuteluluWindow')
root.iconbitmap('heart_green.ico')
root.geometry('500x600')

img=Image.open("Harry Potter.png")
photo=ImageTk.PhotoImage(img)

text=tk.Text()
text.image_create("end",image=photo)
text.insert("end","\n")
text.insert("end","有人也有玩哈利波特嗎?。・∀・ノ゙")
text.pack(fill="both",expand=True)

root.mainloop()

執行結果⬇⬇⬇
https://ithelp.ithome.com.tw/upload/images/20211010/20140047bNEwHU0PPd.png


超爆炸多的程式碼,但裡面都有邏輯,所以只要慢慢去理解很快就會懂了 加油~~~
最近超少玩哈利波特了,但是有在玩槍戰XDD
/images/emoticon/emoticon21.gif


上一篇
Day25 用python寫UI-聊聊Text(二)
下一篇
Day27 用python寫UI-聊聊Treeview(一)
系列文
一起用python寫UI30

尚未有邦友留言

立即登入留言