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


<<:  建立你想要的文化(3)- 落地

>>:  学习Python纪录Day26 - 批次处理档案part2

Day 28 [Python ML、资料清理] 处理字元编码

Get our environment sep up # modules we'll use imp...

Day09 Platform Channel - BasicMessageChannel

如同前面介绍的,Flutter 定义了三种不同型别的Platform Channel 在platfo...

深不可测的海 - Regular Expression

使用终端机搜寻特定字串时,大家一定用过 grep 这个指令吧~ 但你有想过 grep 为什麽叫 gr...

bind, call, apply

在未经过绑定的this会指向Windows Bind 使用Bind会return 一个functio...

Spring boot 与 skaffold

在初始化(skaffold init)时,需先准备好 Dockerfile、K8s 布署资源。然後初...