教你如何使用Python Tkinter库制作记事本


Posted in Python onJune 10, 2021

Tkinter库制作记事本

现在为了创建这个记事本,你的系统中应该已经安装了 Python 3 和 Tkinter。您可以根据系统要求下载合适的python 包。成功安装 python 后,您需要安装 Tkinter(一个 Python 的 GUI 包)。

使用此命令安装 Tkinter :

pip install python-tk

导入 Tkinter :

import tkinter
import os
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *

注意: messagebox用于在称为记事本的白框中写入消息,filedialog用于在您从系统中的任何位置打开文件或将文件保存在特定位置或位置时出现的对话框。

添加菜单:

# Add controls(widget) 
  
self.__thisTextArea.grid(sticky = N + E + S + W) 
  
# To open new file 
self.__thisFileMenu.add_command(label = "New", 
                                command = self.__newFile) 
  
# To open a already existing file 
self.__thisFileMenu.add_command(label = "Open", 
                                command = self.__openFile) 
  
# To save current file 
self.__thisFileMenu.add_command(label = "Save", 
                                command = self.__saveFile) 
  
# To create a line in the dialog 
self.__thisFileMenu.add_separator() 
  
# To terminate 
self.__thisFileMenu.add_command(label = "Exit", 
                                command = self.__quitApplication) 
self.__thisMenuBar.add_cascade(label = "File", 
                               menu = self.__thisFileMenu) 
  
# To give a feature of cut 
self.__thisEditMenu.add_command(label = "Cut", 
                                command = self.__cut) 
  
# To give a feature of copy 
self.__thisEditMenu.add_command(label = "Copy", 
                                command = self.__copy) 
  
# To give a feature of paste 
self.__thisEditMenu.add_command(label = "Paste", 
                                command = self.__paste) 
  
# To give a feature of editing 
self.__thisMenuBar.add_cascade(label = "Edit", 
                               menu = self.__thisEditMenu) 
  
# To create a feature of description of the notepad 
self.__thisHelpMenu.add_command(label = "About Notepad", 
                                command = self.__showAbout) 
self.__thisMenuBar.add_cascade(label = "Help", 
                               menu = self.__thisHelpMenu) 
  
self.__root.config(menu = self.__thisMenuBar) 
  
self.__thisScrollBar.pack(side = RIGHT, fill = Y) 
  
# Scrollbar will adjust automatically 
# according to the content 
self.__thisScrollBar.config(command = self.__thisTextArea.yview) 
self.__thisTextArea.config(yscrollcommand = self.__thisScrollBar.set)

使用此代码,我们将在记事本的窗口中添加菜单,并向其中添加复制、粘贴、保存等内容。

添加功能:

def __quitApplication(self): 
    self.__root.destroy() 
    # exit() 
  
def __showAbout(self): 
    showinfo("Notepad", "Mrinal Verma") 
  
def __openFile(self): 
          
    self.__file = askopenfilename(defaultextension=".txt", 
                                  filetypes=[("All Files","*.*"), 
                                      ("Text Documents","*.txt")]) 
  
    if self.__file == "": 
  
        # no file to open 
        self.__file = None
    else: 
        # try to open the file 
        # set the window title 
        self.__root.title(os.path.basename(self.__file) + " - Notepad") 
        self.__thisTextArea.delete(1.0,END) 
  
        file = open(self.__file,"r") 
  
        self.__thisTextArea.insert(1.0,file.read()) 
  
        file.close() 
  
          
def __newFile(self): 
    self.__root.title("Untitled - Notepad") 
    self.__file = None
    self.__thisTextArea.delete(1.0,END) 
  
def __saveFile(self): 
  
    if self.__file == None: 
        #save as new file 
        self.__file = asksaveasfilename(initialfile='Untitled.txt', 
                                        defaultextension=".txt", 
                                        filetypes=[("All Files","*.*"), 
                                            ("Text Documents","*.txt")]) 
  
        if self.__file == "": 
            self.__file = None
        else: 
              
            # try to save the file 
            file = open(self.__file,"w") 
            file.write(self.__thisTextArea.get(1.0,END)) 
            file.close() 
            # change the window title 
            self.__root.title(os.path.basename(self.__file) + " - Notepad") 
                  
              
    else: 
        file = open(self.__file,"w") 
        file.write(self.__thisTextArea.get(1.0,END)) 
        file.close() 
  
def __cut(self): 
    self.__thisTextArea.event_generate("<<Cut>>") 
  
def __copy(self): 
    self.__thisTextArea.event_generate("<<Copy>>") 
  
def __paste(self): 
    self.__thisTextArea.event_generate("<<Paste>>")

在这里,我们添加了记事本中所需的所有功能,您也可以添加其他功能,例如字体大小、字体颜色、粗体、下划线等。

合并后的主要代码:

import tkinter
import os
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
 
 
class Notepad:
    __root = Tk()
 
    # default window width and height
    __thisWidth = 300
    __thisHeight = 300
    __thisTextArea = Text(__root)
    __thisMenuBar = Menu(__root)
    __thisFileMenu = Menu(__thisMenuBar, tearoff=0)
    __thisEditMenu = Menu(__thisMenuBar, tearoff=0)
    __thisHelpMenu = Menu(__thisMenuBar, tearoff=0)
 
    # To add scrollbar
    __thisScrollBar = Scrollbar(__thisTextArea)
    __file = None
 
    def __init__(self, **kwargs):
 
        # Set icon
        try:
            self.__root.wm_iconbitmap("Notepad.ico")
        except:
            pass
 
        # Set window size (the default is 300x300)
 
        try:
            self.__thisWidth = kwargs['width']
        except KeyError:
            pass
 
        try:
            self.__thisHeight = kwargs['height']
        except KeyError:
            pass
 
        # Set the window text
        self.__root.title("Untitled - Notepad")
 
        # Center the window
        screenWidth = self.__root.winfo_screenwidth()
        screenHeight = self.__root.winfo_screenheight()
 
        # For left-alling
        left = (screenWidth / 2) - (self.__thisWidth / 2)
 
        # For right-allign
        top = (screenHeight / 2) - (self.__thisHeight / 2)
 
        # For top and bottom
        self.__root.geometry('%dx%d+%d+%d' % (self.__thisWidth,
                                              self.__thisHeight,
                                              left, top))
 
        # To make the textarea auto resizable
        self.__root.grid_rowconfigure(0, weight=1)
        self.__root.grid_columnconfigure(0, weight=1)
 
        # Add controls (widget)
        self.__thisTextArea.grid(sticky=N + E + S + W)
 
        # To open new file
        self.__thisFileMenu.add_command(label="New",
                                        command=self.__newFile)
 
        # To open a already existing file
        self.__thisFileMenu.add_command(label="Open",
                                        command=self.__openFile)
 
        # To save current file
        self.__thisFileMenu.add_command(label="Save",
                                        command=self.__saveFile)
 
        # To create a line in the dialog
        self.__thisFileMenu.add_separator()
        self.__thisFileMenu.add_command(label="Exit",
                                        command=self.__quitApplication)
        self.__thisMenuBar.add_cascade(label="File",
                                       menu=self.__thisFileMenu)
 
        # To give a feature of cut
        self.__thisEditMenu.add_command(label="Cut",
                                        command=self.__cut)
 
        # to give a feature of copy
        self.__thisEditMenu.add_command(label="Copy",
                                        command=self.__copy)
 
        # To give a feature of paste
        self.__thisEditMenu.add_command(label="Paste",
                                        command=self.__paste)
 
        # To give a feature of editing
        self.__thisMenuBar.add_cascade(label="Edit",
                                       menu=self.__thisEditMenu)
 
        # To create a feature of description of the notepad
        self.__thisHelpMenu.add_command(label="About Notepad",
                                        command=self.__showAbout)
        self.__thisMenuBar.add_cascade(label="Help",
                                       menu=self.__thisHelpMenu)
 
        self.__root.config(menu=self.__thisMenuBar)
 
        self.__thisScrollBar.pack(side=RIGHT, fill=Y)
 
        # Scrollbar will adjust automatically according to the content
        self.__thisScrollBar.config(command=self.__thisTextArea.yview)
        self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)
 
    def __quitApplication(self):
        self.__root.destroy()
        # exit()
 
    def __showAbout(self):
        showinfo("Notepad", "Mrinal Verma")
 
    def __openFile(self):
 
        self.__file = askopenfilename(defaultextension=".txt",
                                      filetypes=[("All Files", "*.*"),
                                                 ("Text Documents", "*.txt")])
 
        if self.__file == "":
 
            # no file to open
            self.__file = None
        else:
 
            # Try to open the file
            # set the window title
            self.__root.title(os.path.basename(self.__file) + " - Notepad")
            self.__thisTextArea.delete(1.0, END)
 
            file = open(self.__file, "r")
 
            self.__thisTextArea.insert(1.0, file.read())
 
            file.close()
 
    def __newFile(self):
        self.__root.title("Untitled - Notepad")
        self.__file = None
        self.__thisTextArea.delete(1.0, END)
 
    def __saveFile(self):
 
        if self.__file == None:
            # Save as new file
            self.__file = asksaveasfilename(initialfile='Untitled.txt',
                                            defaultextension=".txt",
                                            filetypes=[("All Files", "*.*"),
                                                       ("Text Documents", "*.txt")])
 
            if self.__file == "":
                self.__file = None
            else:
 
                # Try to save the file
                file = open(self.__file, "w")
                file.write(self.__thisTextArea.get(1.0, END))
                file.close()
 
                # Change the window title
                self.__root.title(os.path.basename(self.__file) + " - Notepad")
 
 
        else:
            file = open(self.__file, "w")
            file.write(self.__thisTextArea.get(1.0, END))
            file.close()
 
    def __cut(self):
        self.__thisTextArea.event_generate("<<Cut>>")
 
    def __copy(self):
        self.__thisTextArea.event_generate("<<Copy>>")
 
    def __paste(self):
        self.__thisTextArea.event_generate("<<Paste>>")
 
    def run(self):
 
        # Run main application
        self.__root.mainloop()
 
    # Run main application
 
 
notepad = Notepad(width=600, height=400)
notepad.run()

要运行此代码,请使用扩展名.py保存它,然后打开 cmd(命令提示符)并移动到保存文件的位置,然后编写以下内容

python "filename".py

然后按回车,它就会运行。或者可以通过简单地双击您的.py扩展文件直接运行。

教你如何使用Python Tkinter库制作记事本

到此这篇关于教你如何使用Python Tkinter库制作记事本的文章就介绍到这了,更多相关Tkinter库制作记事本内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python实现简单的TCP代理服务器
Oct 08 Python
在Python中封装GObject模块进行图形化程序编程的教程
Apr 14 Python
Python中的sort()方法使用基础教程
Jan 08 Python
python 将列表中的字符串连接成一个长路径的方法
Oct 23 Python
Python多进程写入同一文件的方法
Jan 14 Python
Python3中urlencode和urldecode的用法详解
Jul 23 Python
python3光学字符识别模块tesserocr与pytesseract的使用详解
Feb 26 Python
树莓派4B安装Tensorflow的方法步骤
Jul 16 Python
Python连接mysql方法及常用参数
Sep 01 Python
详解python tkinter 图片插入问题
Sep 03 Python
python文件目录操作之os模块
May 08 Python
python中取整数的几种方法
Nov 07 Python
Python中常见的反爬机制及其破解方法总结
Jun 10 #Python
Pytorch可视化的几种实现方法
OpenCV-Python实现怀旧滤镜与连环画滤镜
OpenCV-Python实现轮廓的特征值
Jun 09 #Python
再也不用花钱买漫画!Python爬取某漫画的脚本及源码
Jun 09 #Python
Python的这些库,你知道多少?
OpenCV-Python使用cv2实现傅里叶变换
You might like
PHP实现伪静态方法汇总
2016/01/13 PHP
Smarty日期时间操作方法示例
2016/11/15 PHP
PHP实现表单提交数据的验证处理功能【防SQL注入和XSS攻击等】
2017/07/21 PHP
jQuery 选择器、DOM操作、事件、动画
2010/11/25 Javascript
JQuery+CSS提示框实现思路及代码(纯手工打造)
2013/05/07 Javascript
微信小程序 loading(加载中提示框)实例
2016/10/28 Javascript
JavaScript中数组Array方法详解
2017/02/27 Javascript
jQuery插件HighCharts实现的2D条状图效果示例【附demo源码下载】
2017/03/15 Javascript
深入理解Puppeteer的入门教程和实践
2019/03/05 Javascript
基于Vue插入视频的2种方法小结
2019/04/02 Javascript
原生JS实现图片懒加载之页面性能优化
2019/04/26 Javascript
Vue模板语法中数据绑定的实例代码
2019/05/17 Javascript
vue App.vue中的公共组件改变值触发其他组件或.vue页面监听
2019/05/31 Javascript
vue项目中微信登录的实现操作
2020/09/08 Javascript
[57:16]2014 DOTA2华西杯精英邀请赛 5 25 LGD VS VG第二场
2014/05/26 DOTA
Python中实现对list做减法操作介绍
2015/01/09 Python
Python中threading模块join函数用法实例分析
2015/06/04 Python
python opencv人脸检测提取及保存方法
2018/08/03 Python
django框架自定义用户表操作示例
2018/08/07 Python
Python从入门到精通之环境搭建教程图解
2019/09/26 Python
Python字典常见操作实例小结【定义、添加、删除、遍历】
2019/10/25 Python
Flask项目中实现短信验证码和邮箱验证码功能
2019/12/05 Python
python读取dicom图像示例(SimpleITK和dicom包实现)
2020/01/16 Python
浅谈SciPy中的optimize.minimize实现受限优化问题
2020/02/29 Python
基于Django快速集成Echarts代码示例
2020/12/01 Python
中外合拍动画首获奥斯卡提名,“上海出品”《飞奔去月球》能否拿下最终大奖?
2021/03/16 国漫
彻底弄明白CSS3的Media Queries(跨平台设计)
2010/07/27 HTML / CSS
TripAdvisor德国:全球领先的旅游网站
2017/12/07 全球购物
澳大利亚香水在线:Price Rite Mart
2017/12/28 全球购物
门卫岗位职责
2013/11/15 职场文书
幼儿教师研修感言
2014/02/12 职场文书
餐饮商业计划书范文
2014/04/29 职场文书
2014年物流工作总结
2014/11/25 职场文书
个人先进材料范文
2014/12/30 职场文书
CSS 还能这样玩?奇思妙想渐变的艺术
2021/04/27 HTML / CSS
Nginx进程调度问题详解
2021/09/25 Servers