热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用Tkinter

使用Tkinter制作记事本原文:https://www

使用 Tkinter

制作记事本

原文:https://www.geeksforgeeks.org/make-notepad-using-tkinter/

让我们看看如何使用 Tkinter 在 Python 中创建一个简单的记事本。这个记事本图形用户界面将包括各种菜单,如文件和编辑,使用它可以完成所有功能,如保存文件,打开文件,编辑,剪切和粘贴。

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

使用此命令安装 Tkinter :

pip install python-tk

导入 Tkinter :

计算机编程语言

import tkinter
import os
from tkinter import *
# To get the space above for message
from tkinter.messagebox import *
# To get the dialog box to open when required
from tkinter.filedialog import *

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

添加菜单:

计算机编程语言

# 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("<>")
def __copy(self):
    self.__thisTextArea.event_generate("<>")
def __paste(self):
    self.__thisTextArea.event_generate("<>")

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

全部合并后的主代码:

计算机编程语言

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-align
        left = (screenWidth / 2) - (self.__thisWidth / 2)
        # For right-align
        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("<>")
    def __copy(self):
        self.__thisTextArea.event_generate("<>")
    def __paste(self):
        self.__thisTextArea.event_generate("<>")
    def run(self):
        # Run main application
        self.__root.mainloop()
# Run main application
notepad = Notepad(language-py">python "filename".py

然后按回车键,它就会运行。或者只需双击即可直接运行。py 扩展名文件。


推荐阅读
  • 本文介绍了Python对Excel文件的读取方法,包括模块的安装和使用。通过安装xlrd、xlwt、xlutils、pyExcelerator等模块,可以实现对Excel文件的读取和处理。具体的读取方法包括打开excel文件、抓取所有sheet的名称、定位到指定的表单等。本文提供了两种定位表单的方式,并给出了相应的代码示例。 ... [详细]
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • 安装mysqlclient失败解决办法
    本文介绍了在MAC系统中,使用django使用mysql数据库报错的解决办法。通过源码安装mysqlclient或将mysql_config添加到系统环境变量中,可以解决安装mysqlclient失败的问题。同时,还介绍了查看mysql安装路径和使配置文件生效的方法。 ... [详细]
  • 本文介绍了三种方法来实现在Win7系统中显示桌面的快捷方式,包括使用任务栏快速启动栏、运行命令和自己创建快捷方式的方法。具体操作步骤详细说明,并提供了保存图标的路径,方便以后使用。 ... [详细]
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • 开源Keras Faster RCNN模型介绍及代码结构解析
    本文介绍了开源Keras Faster RCNN模型的环境需求和代码结构,包括FasterRCNN源码解析、RPN与classifier定义、data_generators.py文件的功能以及损失计算。同时提供了该模型的开源地址和安装所需的库。 ... [详细]
  • 本文总结了使用不同方式生成 Dataframe 的方法,包括通过CSV文件、Excel文件、python dictionary、List of tuples和List of dictionary。同时介绍了一些注意事项,如使用绝对路径引入文件和安装xlrd包来读取Excel文件。 ... [详细]
  • Python已成为全球最受欢迎的编程语言之一,然而Python程序的安全运行存在一定的风险。本文介绍了Python程序安全运行需要满足的三个条件,即系统路径上的每个条目都处于安全的位置、"主脚本"所在的目录始终位于系统路径中、若python命令使用-c和-m选项,调用程序的目录也必须是安全的。同时,文章还提出了一些预防措施,如避免将下载文件夹作为当前工作目录、使用pip所在路径而不是直接使用python命令等。对于初学Python的读者来说,这些内容将有所帮助。 ... [详细]
  • 通过Anaconda安装tensorflow,并安装运行spyder编译器的完整教程
    本文提供了一个完整的教程,介绍了如何通过Anaconda安装tensorflow,并安装运行spyder编译器。文章详细介绍了安装Anaconda、创建tensorflow环境、安装GPU版本tensorflow、安装和运行Spyder编译器以及安装OpenCV等步骤。该教程适用于Windows 8操作系统,并提供了相关的网址供参考。通过本教程,读者可以轻松地安装和配置tensorflow环境,以及运行spyder编译器进行开发。 ... [详细]
  • tcpdump 4.5.1 crash 深入分析
    tcpdump 4.5.1 crash 深入分析 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • 树莓派Linux基础(一):查看文件系统的命令行操作
    本文介绍了在树莓派上通过SSH服务使用命令行查看文件系统的操作,包括cd命令用于变更目录、pwd命令用于显示当前目录位置、ls命令用于显示文件和目录列表。详细讲解了这些命令的使用方法和注意事项。 ... [详细]
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • 本文讨论了clone的fork与pthread_create创建线程的不同之处。进程是一个指令执行流及其执行环境,其执行环境是一个系统资源的集合。在调用系统调用fork创建一个进程时,子进程只是完全复制父进程的资源,这样得到的子进程独立于父进程,具有良好的并发性。但是二者之间的通讯需要通过专门的通讯机制,另外通过fork创建子进程系统开销很大。因此,在某些情况下,使用clone或pthread_create创建线程可能更加高效。 ... [详细]
  • 本文介绍了Python字典视图对象的示例和用法。通过对示例代码的解释,展示了字典视图对象的基本操作和特点。字典视图对象可以通过迭代或转换为列表来获取字典的键或值。同时,字典视图对象也是动态的,可以反映字典的变化。通过学习字典视图对象的用法,可以更好地理解和处理字典数据。 ... [详细]
author-avatar
缤纷之铃6868
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有