预备知识:
几行代码就可以实现一个窗口:
from tkinter import * compiler = Tk() compiler.title("My Editor") editor = Text() editor.pack() compiler.mainloop()
添加菜单后的效果:
from tkinter import * compiler = Tk() compiler.title("My Editor") menu_bar = Menu(compiler) def run(): print("run") file_menu = Menu(menu_bar,tearoff=0) file_menu.add_command(label='Open',command=run) menu_bar.add_cascade(labe="File",menu=file_menu) run_bar = Menu(menu_bar,tearoff=0) run_bar.add_command(label='Run',command=run) menu_bar.add_cascade(labe="Run",menu=run_bar) compiler.config(menu=menu_bar) editor = Text() editor.pack() compiler.mainloop()
一、项目一
(一)成果展示
(二)代码:
from tkinter import * root = Tk() root.title("www.snailtoday.com") # root.iconbitmap("c:/gui/codemy.ico") root.geometry("500x300") #Update the listbox def update(data): #clear the listbox my_list.delete(0,END) #add toppings to listbox for item in data: my_list.insert(END,item) #update entry box with listbox clicked def fillout(e): #delete whatever is in the entry box my_entry.delete(0,END) #ADD clicked list item to entry box my_entry.insert(0, my_list.get(ACTIVE)) #create function to check entry vs listbox def check(e): #grab what was typed typed = my_entry.get() if type == '': data = toppings else: data = [] for item in toppings: if typed.lower() in item.lower(): data.append(item) #upadate our listbox with selected item update(data) #create a label my_label = Label(root,text="start Typing...",font=("helvetica",14),fg="grey") my_label.pack(pady=20) #create an entry box my_entry = Entry(root,font=("helvetica",20)) my_entry.pack() #create a list my_list = Listbox(root,width=50) my_list.pack(pady=40) #Create a list toppings = ["pepperoni","Peppers","Mushrooms","Cheese","Onions","Ham","Taco"] #add the toppings to our list update(toppings) #Create a binding on the listbox onclick my_list.bind("<<ListboxSelect>>", fillout) #create a binding on the entry box my_entry.bind("<KeyRelease>",check) root.mainloop()
参考:https://pythonguides.com/python-tkinter-autocomplete/
二、项目二
(一)成果展示
(二)代码
from ttkwidgets.autocomplete import AutocompleteCombobox from tkinter import * countries = [ 'Antigua and Barbuda', 'Bahamas','Barbados','Belize', 'Canada', 'Costa Rica ', 'Cuba', 'Dominica', 'Dominican Republic', 'El Salvador ', 'Grenada', 'Guatemala ', 'Haiti', 'Honduras ', 'Jamaica', 'Mexico', 'Nicaragua', 'Saint Kitts and Nevis', 'Panama ', 'Saint Lucia', 'Saint Vincent and the Grenadines', 'Trinidad and Tobago', 'United States of America' ] ws = Tk() ws.title('PythonGuides') ws.geometry('400x300') ws.config(bg='#8DBF5A') frame = Frame(ws, bg='#8DBF5A') frame.pack(expand=True) Label( frame, bg='#8DBF5A', font = ('Times',21), text='Countries in North America ' ).pack() entry = AutocompleteCombobox( frame, width=30, font=('Times', 18), completevalues=countries ) entry.pack() ws.mainloop()
三、项目三
(一)成果展示
(二)代码
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("<<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()
参考:
https://www.youtube.com/watch?v=iyJ1_ODzNUk
https://www.geeksforgeeks.org/make-notepad-using-tkinter/
四、
https://doc.qt.io/qt-5/qtwidgets-tools-customcompleter-example.html
五、另外一种方案
https://sourceforge.net/projects/npp-python/files/1.2/
不过同样存在这个缺点,它只能自动完成函数,不能自动完成带空格的内容。
python.xml文件要放到C:\Program Files (x86)\Notepad++\plugins\APIs,且不能改名。
六、自己的方案
import sqlite3 from tkinter import * from tkinter import filedialog from tkinter import font root = Tk() root.title("豆芽写作助手V1.0") # root.iconbitmap("c:/gui/codemy.ico") root.geometry("1850x800") #Set variable for open file name global open_status_name open_status_name =False global selected selected = False #create main frame my_frame = Frame(root) my_frame.pack(pady=5) #create sroll bar text_scroll = Scrollbar(my_frame) text_scroll.pack(side=RIGHT,fill=Y) #create text box my_text = Text(my_frame,width=197, height=16,font=("Helvetica",16),undo=True) my_text.pack(pady=5) #configure our scrollbar text_scroll.config(command = my_text.yview) # add status bar to bottom of App status_bar = Label(root,text='Ready ',anchor=E) status_bar.pack(fill=X,side=BOTTOM,ipady=5) #Create New file function def new_file(): my_text.delete("1.0",END) #update status bars root.title("New File - TextPad!") status_bar.config(text="New File ") global open_status_name open_status_name =False def open_file(): #delete previous text my_text.delete("1.0",END) #Grab filename text_file = filedialog.askopenfilename(initialdir="C:\gui",title="Open file",filetypes=(("Text Files","*.txt"),("HTML FIles","*.html"),("All Files","*.*"))) #check to see if there is a file name if text_file: #make filename global,so we can access it later. global open_status_name open_status_name =text_file #update status bars name = text_file status_bar.config(text=f'{name} ') name = name.replace("H:\\py_project\\编辑器开发","") root.title(f'{name}' "- TextPad!") #open the file text_file = open(text_file,'r') stuff = text_file.read() my_text.insert(END,stuff) #close the opend file text_file.close() def save_as_file(): text_file = filedialog.asksaveasfilename(defaultextension=".*",initialdir="C:\gui",title="Open file",filetypes=(("Text Files","*.txt"),("HTML FIles","*.html"),("All Files","*.*"))) if text_file: name = text_file #update status bars status_bar.config(text=f'Saved {name} ') name = name.replace("H:\\py_project\\编辑器开发","") root.title(f'{name}' "- TextPad!") #save the file text_file = open(text_file,"w") text_file.write(my_text.get(1.0,END)) text_file.close() def save_file(): global open_status_name if open_status_name: #save the file text_file = open(open_status_name,"w") text_file.write(my_text.get(1.0,END)) text_file.close() status_bar.config(text=f'Saved {open_status_name} ') else: save_as_file() def cut_text(e): global selected if e: selected = root.clipboard_get() else: if my_text.selection_get(): #grab selected text from text box selected = my_text.selection_get() #delete selected text from text box my_text.delete("sel.first","sel.last") #clear the clipboard then append root.clipboard_clear() root.clipboard_append(selected) def copy_text(e): global selected if e: selected = root.clipboard_get() if my_text.selection_get(): #grab selected text from text box selected = my_text.selection_get() #clear the clipboard then append root.clipboard_clear() root.clipboard_append(selected) def paste_text(e): global selected if e: selected = root.clipboard_get() else: if selected: position = my_text.index(INSERT) my_text.insert(position,selected) #create Menu my_menu = Menu(root) root.config(menu=my_menu) #Add file menu file_menu = Menu(my_menu,tearoff = False) my_menu.add_cascade(label="File",menu= file_menu) file_menu.add_command(label="New",command= new_file) file_menu.add_command(label="Open",command= open_file) file_menu.add_command(label="Save",command= save_file) file_menu.add_command(label="Save As",command= save_as_file) file_menu.add_separator() file_menu.add_command(label="Exit",command=root.quit) #Add edit menu edit_menu = Menu(my_menu,tearoff = False) my_menu.add_cascade(label="Edit",menu= edit_menu) edit_menu.add_command(label="Cut",command= lambda: cut_text(False)) edit_menu.add_command(label="Copy",command= lambda: copy_text(False)) edit_menu.add_command(label="Paste",command= lambda: paste_text(False)) edit_menu.add_separator() edit_menu.add_command(label="undo",command= my_text.edit_undo) edit_menu.add_command(label="Redo",command= my_text.edit_redo) #Update the listbox def update(data): #clear the listbox my_list.delete(0,END) #add toppings to listbox for item in data: my_list.insert(END,item) #update entry box with listbox clicked def fillout(e): #delete whatever is in the entry box my_entry.delete(0,END) #ADD clicked list item to entry box my_entry.insert(0, my_list.get(ACTIVE)) #create function to check entry vs listbox def check(e): #grab what was typed typed = my_entry.get() if type == '': data = toppings else: data = [] for item in toppings: if typed.lower() in item.lower(): data.append(item) #upadate our listbox with selected item update(data) #create a label my_label = Label(root,text="Start Typing...",font=("helvetica",14),fg="grey") my_label.pack(pady=0) #滚动条组件 sb = Scrollbar(root) sb.pack(side=RIGHT,fill=Y) #create an entry box my_entry = Entry(root,font=("helvetica",20),width=180) my_entry.pack() #create a list my_list = Listbox(root,font=("Arial",16),width=1800,height=20,yscrollcommand=sb.set) my_list.pack(pady=5,side=LEFT,fill=BOTH) sb.config(command=my_list.yview) #Create a list # toppings = ["pepperoni","Peppers","Mushrooms","Cheese","Onions","Ham","Taco"] connection = sqlite3.connect('bbc_sentence.db') cur = connection.cursor() cur.execute("select content from business_begin") sqloutput = cur.fetchall() #This contains the SQL output in format [(u'data1',), (u'data2',), (u'data3',)] toppings = [item[0] for item in sqloutput] #This is manipulated to the format [u'data1',u'data2',u'data3'] #add the toppings to our list update(toppings) #Create a binding on the listbox onclick my_list.bind("<<ListboxSelect>>", fillout) #create a binding on the entry box my_entry.bind("<KeyRelease>",check) root.mainloop()