我正在尝试使用python
Gui在Tkinter
中创建简单的记事本。在这里我创建了custom_notebook小部件,因为我需要关闭标签中的按钮。但是当我在笔记本中添加标签时,其创建列表Text()
小部件,并将它们添加到名为_Text[]
的列表中。一切都进行到此处,直到我开始关闭tabs.close选项卡列表保持不变,因为我不从列表中删除文本小部件存储位置,因为关闭事件时我不知道如何从列表中删除正确的文本小部件存储位置发生这种情况及其对其他新标签的创建问题,例如将标签标签留空并覆盖其他内容。
import tkinter.ttk as ttk
import tkinter as tk
from tkinter import BOTH,LEFT,RIGHT,X,Y,filedialog,INSERT
from os import getcwd
from os.path import exists
class CustomNotebook(ttk.Notebook):
__initialized = False
def __init__(self, *args, **kwargs):
if not self.__initialized:
self.__initialize_custom_style()
self.__inititialized = True
kwargs["style"] = "CustomNotebook"
ttk.Notebook.__init__(self, *args, **kwargs)
self._active = None
self.bind("<ButtonPress-1>", self.on_close_press, True)
self.bind("<ButtonRelease-1>", self.on_close_release)
def on_close_press(self, event):
"""Called when the button is pressed over the close button"""
element = self.identify(event.x, event.y)
if "close" in element:
index = self.index("@%d,%d" % (event.x, event.y))
self.state(['pressed'])
self._active = index
def on_close_release(self, event):
"""Called when the button is released over the close button"""
if not self.instate(['pressed']):
return
element = self.identify(event.x, event.y)
index = self.index("@%d,%d" % (event.x, event.y))
if "close" in element and self._active == index:
self.forget(index)
self.event_generate("<<NotebookTabClosed>>")
self.state(["!pressed"])
self._active = None
def __initialize_custom_style(self):
style = ttk.Style()
self.images = (
tk.PhotoImage("img_close", data='''
R0lGODlhCAAIAMIBAAAAADs7O4+Pj9nZ2Ts7Ozs7Ozs7Ozs7OyH+EUNyZWF0ZWQg
d2l0aCBHSU1QACH5BAEKAAQALAAAAAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU
5kEJADs=
'''),
tk.PhotoImage("img_closeactive", data='''
R0lGODlhCAAIAMIEAAAAAP/SAP/bNNnZ2cbGxsbGxsbGxsbGxiH5BAEKAAQALAAA
AAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU5kEJADs=
'''),
tk.PhotoImage("img_closepressed", data='''
R0lGODlhCAAIAMIEAAAAAOUqKv9mZtnZ2Ts7Ozs7Ozs7Ozs7OyH+EUNyZWF0ZWQg
d2l0aCBHSU1QACH5BAEKAAQALAAAAAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU
5kEJADs=
''')
)
style.element_create("close", "image", "img_close",
("active", "pressed", "!disabled", "img_closepressed"),
("active", "!disabled", "img_closeactive"), border=8, sticky='')
style.layout("CustomNotebook", [("CustomNotebook.client", {"sticky": "nswe"})])
style.layout("CustomNotebook.Tab", [
("CustomNotebook.tab", {
"sticky": "nswe",
"children": [
("CustomNotebook.padding", {
"side": "top",
"sticky": "nswe",
"children": [
("CustomNotebook.focus", {
"side": "top",
"sticky": "nswe",
"children": [
("CustomNotebook.label", {"side": "left", "sticky": ''}),
("CustomNotebook.close", {"side": "left", "sticky": ''}),
]
})
]
})
]
})
])
class Main:
def __init__(self,master):
self.master = master
self._tabs = []
self._Text = []
self.i = 0
self.master.filename = ""
self.win = ttk.Frame(self.master)
self.Tabs_frame = CustomNotebook(self.win)
self.Tabs_frame.pack(fill=BOTH,expand=1)
self.win.pack()
self._ad_tabs()
self.master.bind('<Control-n>',self._ad_tabs)
self.master.bind('<Control-s>',self.save_file)
self.master.bind('<Control-w>',self._saveAs)
self.master.bind('<Control-o>',self.Open_file)
def _ad_tabs(self,event=None,data=None):
self._tabs.append(ttk.Frame(self.Tabs_frame))
self.Tabs_frame.add(self._tabs[self.i],text="untitled")
self.txt = ttk.tkinter.Text(self._tabs[self.i],undo=True)
self._Text.append(self.txt)
self._Text[self.i].pack(fill=BOTH,expand=1)
if data != None:
self._Text[self.i].insert(INSERT,data)
self.Tabs_frame.tab(self.i,text=self.master.filename)
self.i = self.i+1
print(self._Text)
def Open_file(self,event=None):
crdir = getcwd()
workspace = crdir+"\\Workspace"
self.master.filename = filedialog.askopenfilename(initialdir=workspace,title="open",
filetypes=(("All types","*.*"),
("Text File","*.txt")))
if self.master.filename != "":
fopen = open(self.master.filename,"r")
frd = fopen.read()
if self.Tabs_frame.tab(self.Tabs_frame.select(),"text") !="untitled":
self._ad_tabs(None,frd)
else:
self._Text[self.Tabs_frame.index('current')].insert(INSERT,frd)
self.Tabs_frame.tab(self.Tabs_frame.index('current'),text=self.master.filename)
fopen.close()
def save_file(self,event=None):
c_name = self.Tabs_frame.tab(self.Tabs_frame.select(),"text")
if c_name == "untitled":
self.master.filename = filedialog.asksaveasfilename(title="Save",
filetypes=(("All types","*.*"),
("Text file","*.txt")))
if self.master.filename != "":
_txt_id2 = self.Tabs_frame.index('current')
self.get_input = self._Text[_txt_id2].get("1.0","end-1c")
print(self.get_input)
with open(self.master.filename,"w") as f:
f.write(self.get_input)
self.Tabs_frame.tab(_txt_id2,text=self.master.filename)
if exists(self.master.filename)==True:
crnt_tab_name = self.Tabs_frame.tab(self.Tabs_frame.select(),"text")
if crnt_tab_name != "untitled":
self.master.filename = crnt_tab_name
if crnt_tab_name == self.master.filename:
_txt_id = self.Tabs_frame.index('current')
if self.master.filename != "" and self.master.filename != "untitled":
self.get_input = self._Text[_txt_id].get("1.0","end-1c")
with open(self.master.filename,"w") as f:
f.write(self.get_input)
self.Tabs_frame.tab(_txt_id,text=self.master.filename)
def _saveAs(self):
self._crnt_tab = self.Tabs_frame.index('current')
self.master.filename = filedialog.asksaveasfilename(title="Save",
filetypes=(("All types","*.*"),
("text file","*.txt")))
if self.master.filename != "":
if exists(self.master.filename)==False:
self.get_input = self._Text[self._crnt_tab].get("1.0","end-1c")
print(self.get_input)
with open(self.master.filename,"w") as f:
f.write(self.get_input)
self.Tabs_frame.tab(self._crnt_tab,text=self.master.filename)
if __name__ == "__main__":
root = ttk.tkinter.Tk()
Main(root)
root.mainloop()