txt文件编辑器(v4.0)

家电维修 2023-07-16 19:16www.caominkang.com家电维修技术

1、介绍

环境python3.8-3.10

导入包in32api,in32con,tkinter,time,easygui,os,threading

废话不多说,先上源代码

import in32api,in32con
import tkinter
import tkinter as tk
import tkinter.filedialog
import tkinter.messagebox
import tkinter.scrolledtext
import tkinter.colorchooser
import tkinter.simpledialog
import time
import easygui as g
import tkinter
import tkinter.messagebox
import os
#import virtkey
from pynput.keyboard import Key, Controller
from tkinter import 
from tkinter.scrolledtext import ScrolledText
from tkinter import messagebox
from threading import Thread
from tkinter.ttk import 

# ----------------------------------------一、创建窗口-------------------------------------------------
filename = ""  # 定义空文件名
in = tk.Tk()
in.title('WSL文件编辑器')
in["height"] = 400
in["idth"] = 600
# ----------------------------------------特殊---------------------------------------------------------

def quit_exit():
 global filename
 if textChanged.get():
  yesno = tk.messagebox.askyesno(
   title="提醒", message="你想保存吗?")  # 询问框
  if yesno == tkinter.YES:
   if not filename:
    SaveAs()
   else:
    Save()
  else:
   exit()
   #in.destroy()
 else:
  exit()
  #in.destroy()
 exit()
 #in.destroy()

def popup(event):
 right.post(event.x_root,event.y_root)
 
# ---------------------------------------二、功能定义区---------------------------------------------

mylist=[]

# -----------------------------------------1.菜单栏 File-----------------------------------------------------------

textChanged = tk.IntVar(value=0)  # 字符串计数器

# 1.打开


def Open():
 global filename
 # 1.获取字符,是否保存原来的文档
 if textChanged.get():
  yesno = tk.messagebox.askyesno(
   title="提醒", message="你想保存吗?")  # 询问框

  if yesno == tkinter.YES:
   Save()
  #filename = tkinter.filedialog.askopenfilename(
  # title="Open file", filetypes=[("Text files", ".txt")])  # 打开路径框
  #filename = g.fileopenbox(default=".txt")
 # 2.打开新的文档
 
 #filename = g.fileopenbox("打开","",".txt")
 
 filename = tkinter.filedialog.askopenfilename(
  title="打开", filetypes=[("Text files", ".txt")])  # 打开路径框
 if filename:
  mylist.append(filename)
  (filepath,tempfilename) = os.path.split(filename)
  (file_name,extension) = os.path.splitext(tempfilename)
  if filename!="":
   in.title('WSL文件编辑器-'+file_name)
  else:
   in.title('WSL文件编辑器')
  txtContent.delete(0.0, tk.END)  # 删除原来的文本
  #filename = tkinter.filedialog.askopenfilename(
  # title="Open file", filetypes=[("Text files", ".txt")])  # 打开路径框
  #filename = g.fileopenbox(default=".txt")
  fp = open(filename, "rb")  # 读取文本
  txtContent.insert(tkinter.INSERT, "".join(
   fp.read().decode('GBK')))  # 解码插入到文本编辑器
  fp.close()  # 关闭指针
  textChanged.set(0)  # 字符串置0

# 2.保存


def Save():
 global filename
 if not filename:
  SaveAs()

 elif textChanged.get():
  fp = open(filename, "")  # 创建文本
  fp.rite(txtContent.get(0.0, tkinter.END))  # 将文本框的内容导入文件
  fp.close()  # 关闭
  #in32api.MessageBox(0, "保存完毕", "WSL文件编辑器·保存",in32con.MB_OK)
  textChanged.set(0)  # 计数器置0
  #in32api.MessageBox(0, "保存完毕", "WSL文件编辑器·保存",in32con.MB_OK)
  #indos=Tk()
  #indos.title("使用说明")
  #indos.geometry("200x100+200+100")
  #name="""保存完毕"""
  #listbox = ScrolledText(indos)
  #listbox.place(x=0, y=0, idth=500, height=300)
  #listbox.insert(tkinter.END, name)
  #listbox.insert(tkinter.END, name)
  #listbox.see(tkinter.END)         # ScrolledText组件方法,自动定位到结尾,否则只有消息在涨,窗口拖动条不动
  #listbox.update()
  #time.sleep(3)
  #indos.destroy()
 if filename:
  in32api.MessageBox(0, "保存完毕", "WSL文件编辑器·保存",in32con.MB_OK)

# 3.保存到


def SaveAs():
 global filename
 # 创建对话框,默认对应的路径和文件名
 nefilename = tkinter.filedialog.asksaveasfilename(
  title="另存为", initialdir=r"c:\", initialfile="ne.txt")

 # 写入文件内容
 if nefilename:
  mylist.append(filename)
  (filepath,tempfilename) = os.path.split(nefilename)
  (file_name,extension) = os.path.splitext(tempfilename)
  in.title('WSL文件编辑器-'+file_name)
  fp = open(nefilename, "")
  fp.rite(txtContent.get(0.0, tkinter.END))
  fp.close()
  filename = nefilename

  textChanged.set(0)

# 4.删除


def Remove():
 global filename
 if filename!="":
  os.remove(filename)
  #filename = tkinter.filedialog.askopenfilename(
  # title="打开", filetypes=[("Text files", ".txt")])  # 打开路径框
  filename=""
  in.title('WSL文件编辑器')
  if filename:
   mylist.append(filename)
   #submenu4.add_mand(label=filename)#, mand=
   (filepath,tempfilename) = os.path.split(filename)
   (file_name,extension) = os.path.splitext(tempfilename)
   if filename!="":
    in.title('WSL文件编辑器-'+file_name)
   else:
    in.title('WSL文件编辑器')
   txtContent.delete(0.0, tk.END)  # 删除原来的文本
   #filename = tkinter.filedialog.askopenfilename(
   # title="Open file", filetypes=[("Text files", ".txt")])  # 打开路径框
   #filename = g.fileopenbox(default=".txt")
   fp = open(filename, "rb")  # 读取文本
   txtContent.insert(tkinter.INSERT, "".join(
    fp.read().decode('GBK')))  # 解码插入到文本编辑器
   fp.close()  # 关闭指针
   textChanged.set(0)  # 字符串置0
  else:
   in.title('WSL文件编辑器')
 else:
  messagebox.shoerror("WSL文件编辑器","未打开文件 ")
# 5.关闭


def Close():
 global filename
 Save()  # 保存
 txtContent.delete(0.0, tkinter.END)  # 区域置空
 filename = ""  # 文件名置空
 (filepath,tempfilename) = os.path.split(filename)
 (file_name,extension) = os.path.splitext(tempfilename)
 if filename!="":
  in.title('WSL文件编辑器-'+file_name)
 else:
  in.title('WSL文件编辑器')


# -------------------------------------------2.菜单栏 Edit-----------------------------------------------------------
# 1.回退
def Undo():
 txtContent["undo"] = True
 try:
  txtContent.edit_undo()
 except Exception as e:
  pass

# 2.前进


def Redo():
 txtContent["undo"] = True
 try:
  txtContent.edit_redo()
 except Exception as e:
  pass

# 3.复制


def Copy():
 try:
  txtContent.clipboard_clear()  # 清空缓冲区
  txtContent.clipboard_append(txtContent.selection_get())  # 保存到缓冲区#txtContent.selection_get()
 except Exception as e:
  pass
 pass

# 4.剪切


def Cut():
 Copy()  # 复制文本
 try:
  txtContent.delete(tkinter.SEL_FIRST, tkinter.SEL_LAST)  # 删除文本编译器的选中文本
 except Exception as e:
  pass

# 5.粘贴
def paste():
 time.sleep (0.1)
 keyboard = Controller()
 keyboard.press(Key.ctrl.value )#Key.cmd.value
 keyboard.press('v')
 keyboard.release('v')
 #time.sleep (0.5)
 keyboard.release(Key.ctrl.value )
def Paste():
 #time.sleep (0.1)
 #keyboard = Controller()
 #keyboard.press(Key.ctrl.value )#Key.cmd.value
 #keyboard.press('v')
 #keyboard.release('v')
 #time.sleep (0.5)
 #keyboard.release(Key.ctrl.value )
 #keyboard.release('v')
 try:
  txtContent.insert(tkinter.SEL_FIRST,
        txtContent.clipboard_get())  # 获取缓冲区文本
  #time.sleep (0.3)
  #keyboard = Controller()
  #keyboard.press(Key.cmd.value )#Key.ctrl.value
  #keyboard.press(tkinter.SEL_FIRST)
  #time.sleep (0.5)
  #keyboard.release(Key.ctrl.value )
  #keyboard.release('v')
  #v = virtkey.virtkey()
  #v.press_keysym(65507) #Ctrl键位
  #v.press_unicode(ord('v')) #模拟字母V
  #v.release_unicode(ord('v'))
  #v.release_keysym(65507)
  txtContent.delete(tkinter.SEL_FIRST, tkinter.SEL_LAST)  # 删除选中文本
  return
 except Exception as e:
  paste()
  pass

# 6.查找


def Search():
 textToSearch = tkinter.simpledialog.askstring(
  title="查找", prompt="你想找什么?")
 try:
  start = txtContent.search(textToSearch, 0.0, tkinter.END)
  if start:  # 查找到时,返回yes
   tkinter.messagebox.shoinfo(title="存在", message="存在")
 except Exception as e:
  pass


# --------------------------------------------3.菜单栏 Help-----------------------------------------------------------
# 1,关于
def About():
 #tkinter.messagebox.shoinfo(
 # title="关于", message="作者:Wesley")  # 弹出信息框
 in32api.MessageBox(0, "作者:Wesley", "关于",in32con.MB_OK)
 pass

#使用说明

def Explain():
 indos=Tk()
 indos.title("使用说明")
 indos.geometry("500x300+200+100")
 name="""
 			WSL文件编辑器使用说明

 [文件]功能:打开、保存、另存为、删除、关闭
 [编辑]功能:上一部、下一步、复制、剪切、粘贴、查找
 [帮助]功能:关于、说明、字体"""
 listbox = ScrolledText(indos)
 listbox.place(x=0, y=0, idth=500, height=300)
 try:
  hile True:
   listbox.insert(tkinter.END, name)
   #listbox.insert(tkinter.END, name)
   listbox.see(tkinter.END)         # ScrolledText组件方法,自动定位到结尾,否则只有消息在涨,窗口拖动条不动
   listbox.update()
   #time.sleep(0.01)
   listbox.delete(0.0, tk.END)
 except Exception as e:
  pass
 
#

def Write():
 global filename
 global txtContent
 def ae():
  global filename
  global txtContent
  #txtContent.destroy()
  if entry.get()!="":
   if int(entry.get())>3 and int(entry.get())<85:
    txtContent.config(font=("宋体", int(entry.get())))
  """txtContent = tk.scrolledtext.ScrolledText(in, rap=tk.WORD,font=("宋体",int(entry.get())))
  txtContent.pack(fill=tk.BOTH, expand=tkinter.YES)
  in.geometry('600x400+600+400')
  if filename:
   (filepath,tempfilename) = os.path.split(filename)
   (file_name,extension) = os.path.splitext(tempfilename)
   if filename!="":
    in.title('WSL文件编辑器-'+file_name)
   else:
    in.title('WSL文件编辑器')
   txtContent.delete(0.0, tk.END)  # 删除原来的文本
   #filename = tkinter.filedialog.askopenfilename(
   # title="Open file", filetypes=[("Text files", ".txt")])  # 打开路径框
   #filename = g.fileopenbox(default=".txt")
   fp = open(filename, "rb")  # 读取文本
   txtContent.insert(tkinter.INSERT, "".join(
    fp.read().decode('GBK')))  # 解码插入到文本编辑器
   fp.close()  # 关闭指针
   textChanged.set(0)  # 字符串置0"""
 def 重置():
  txtContent.config(font=("宋体", 10))
 r1=Tk()
 r1.title('WSL文件编辑器·字体')
 r1.geometry('300x270+300+300')

 #内容
 label=Label(r1,text='字体大小(4到84之内):')#进入聊天室之前,先起一个
 label.pack(anchor='c',pady=20)

 #输入框
 entry=Entry(r1,idth=18)
 entry.pack(anchor='c',pady=20)

 #按钮
 button=Button(r1,text='确认',mand=ae)
 button.pack(anchor='c',pady=20)

 button=Button(r1,text='重置',mand=重置)
 button.pack(anchor='c',pady=20)
 #r1.mainloop()

# -------------------------------------------------------------------------------------------------------------------

# ------------------------------------三、菜单栏框架----------------------------------
menu1 = tk.Menu(in)

# 菜单1 File
# ---------------------------------------------------------------------
submenu = tk.Menu(menu1, tearoff=0)

submenu.add_mand(label="打开", mand=Open)
#submenu.add_separator()
submenu.add_mand(label="保存", mand=Save)
#submenu.add_separator()
submenu.add_mand(label="另存为", mand=SaveAs)
#submenu.add_separator()
submenu.add_mand(label="删除", mand=Remove)
#submenu.add_separator()
submenu.add_mand(label="关闭", mand=Close)

menu1.add_cascade(label="文件", menu=submenu)
# -----------------------------------------------------------------------


# 菜单2  Edit
# -----------------------------------------------------------------------
submenu2 = tk.Menu(menu1, tearoff=0)

submenu2.add_mand(label="上一步", mand=Undo)
#submenu2.add_separator()
submenu2.add_mand(label="下一步", mand=Redo)
#submenu2.add_separator()
submenu2.add_mand(label="复制", mand=Copy)
#submenu2.add_separator()
submenu2.add_mand(label="剪切", mand=Cut)
#submenu2.add_separator()
submenu2.add_mand(label="粘贴", mand=Paste)
#submenu2.add_separator()
submenu2.add_mand(label="查找", mand=Search)

menu1.add_cascade(label="编辑", menu=submenu2)
# ------------------------------------------------------------------------


# 菜单3 Help
# ------------------------------------------------------------------------
submenu3 = tk.Menu(menu1, tearoff=0)

submenu3.add_mand(label="关于", mand=About)

submenu3.add_mand(label="说明", mand=Explain)

submenu3.add_mand(label="字体", mand=Write)

menu1.add_cascade(label="帮助", menu=submenu3)
# ------------------------------------------------------------------------


# 右键菜单
# ----------------------------------------------------------------------------------------------------------
right = tk.Menu(menu1, tearoff=0)
#1
#right.add_mand(label="打开", mand=Open)
#submenu.add_separator()
#right.add_mand(label="保存", mand=Save)
#submenu.add_separator()
#right.add_mand(label="另存为", mand=SaveAs)
#submenu.add_separator()
#right.add_mand(label="删除", mand=Remove)
#submenu.add_separator()
#right.add_mand(label="关闭", mand=Close)
#
#right.add_separator()
#2
right.add_mand(label="上一步", mand=Undo)
#submenu2.add_separator()
right.add_mand(label="下一步", mand=Redo)
#submenu2.add_separator()
right.add_mand(label="复制", mand=Copy)
#submenu2.add_separator()
right.add_mand(label="剪切", mand=Cut)
#submenu2.add_separator()
right.add_mand(label="粘贴", mand=Paste)
#submenu2.add_separator()
right.add_mand(label="查找", mand=Search)
#
#right.add_separator()
#3
#right.add_mand(label="关于", mand=About)
#right.add_mand(label="说明", mand=Explain)
#right.add_mand(label="字体", mand=Write)

# ------------------------------------------四、总体结构---------------------------------
# 1.菜单栏
in.config(menu=menu1)

# 2.滑动文本框

key=False
def keyPress(event):
 global key
 if key==False:
  textChanged.set(1)

def keydon(event):
 global key
 #print("c")
 def a():
  global key
  time.sleep(0.5)
  key=False
 key=True
 #t1=Thread(target=a)
 #t1.start()
"""
def key_():
 if key==True:
 key=False
"""
def key_s(event):
 global key
 if key==True:
  Save()
 key=False
def key_z(event):
 global key
 if key==True:
  Undo()
 key=False
def ne_key_z(event):
 Undo()
def keykey(event):
 Redo()
def save(event):
 Save()
def keyup(event):
 global key
 key=False
#def key_():
in.protocol("WM_DELETE_WINDOW", quit_exit)
txtContent = tk.scrolledtext.ScrolledText(in, rap=tk.WORD)#txtContent = tk.scrolledtext.ScrolledText(indo, idth=70, height=13,font=("宋体",18))
txtContent.pack(fill=tk.BOTH, expand=tkinter.YES)  # 创建

txtContent.bind("", keyPress)  # 绑定按键识别器
txtContent.bind("", keydon)
txtContent.bind("s", key_s)
txtContent.bind('', keyup)
txtContent.bind("z", key_z)
#txtContent.bind("Control-KeyPress-S", save)
#txtContent.bind("Control-KeyPress-Z", ne_key_z)
txtContent.bind("", keykey)
#txtContent.bind("", key_shift)
txtContent.bind("",popup)
#txtContent.bind("", key_)
#
in.mainloop()
"""
try:
 pass
except Exception as e:
 pass
"""

由于没时间介绍太多代码,作者就先不介绍了,自己看注释。

旧功能

[文件]功能:打开、保存、另存为、删除、关闭

 [编辑]功能:上一部、下一步、复制、剪切、粘贴、查找

[帮助]功能:关于、说明、字体

退出提醒是否保存

静止改编说明

新功能

修复了一些功能

增加了右键菜单

快捷键

Ctrl+s                     保存

Ctrl+z                     上一步

Ctrl+Shift+z            下一步

运行截图

 

个人主页https://blog.csdn./puter123_ind?spm=1011.2266.3001.5343

Copyright © 2016-2025 www.jianfeikang.com 建飞家电维修 版权所有 Power by