tcl Error in Tkinter - python

I'm using this code to make a text editor and I'm trying to add menus and shortcuts I will implant that later as of now I don't know how to do that(thats another question another day though if you know the answer please share it. but anyway I'm getting this error and i don't know why.
Error:
Traceback (most recent call last):
File "C:\Python27\Completed Projects\editor.py", line 90, in <module>
Editor().mainloop()
File "C:\Python27\Completed Projects\editor.py", line 52, in __init__
filemenu.add_command(text='Save', command=self.onSave).pack(side=LEFT)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2683, in add_command
self.add('command', cnf or kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2674, in add
self._options(cnf, kw))
TclError: unknown option "-text"
and the code:
from Tkinter import *
from tkSimpleDialog import *
from tkFileDialog import *
from tkMessageBox import *
root = Tk()
menubar = Menu(root)
class QuitMe(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.pack()
widget = Button(self, text='Quit', command=self.quit)
widget.pack(expand=YES, fill=BOTH, side=LEFT)
def quit(self):
ans = askokcancel('Confirm exit', "Sure you want to Quit?")
if ans: Frame.quit(self)
class ScrolledText(Frame):
def __init__(self, parent=None, text='', file=None):
Frame.__init__(self, parent)
self.pack(expand=YES, fill=BOTH)
self.makewidgets()
self.settext(text, file)
def makewidgets(self):
sbar = Scrollbar(self)
text = Text(self, relief=SUNKEN)
sbar.config(command=text.yview)
text.config(yscrollcommand=sbar.set)
sbar.pack(side=RIGHT, fill=Y)
text.pack(side=LEFT, expand=YES, fill=BOTH)
self.text = text
def settext(self, text='', file=None):
if file:
text = open(file, 'r').read()
self.text.delete('1.0', END)
self.text.insert('1.0', text)
self.text.mark_set(INSERT, '1.0')
self.text.focus()
def gettext(self):
return self.text.get('1.0', END+'-1c')
class Editor(ScrolledText):
def __init__(self, parent=None, file=None):
frm = Frame(parent)
frm.pack(fill=X)
filemenu = Menu(menubar, tearoff=0)
editmenu = Menu(menubar, tearoff=0)
filemenu.add_command(text='Save', command=self.onSave).pack(side=LEFT)
editmenu.add_command(text='Cut', command=self.onCut).pack(side=LEFT)
editmenu.add_command(text='Paste', command=self.onPaste).pack(side=LEFT)
editmenu.add_command(text='Find', command=self.onFind).pack(side=LEFT)
QuitMe(frm).pack(side=LEFT)
ScrolledText.__init__(self, parent, file=file)
self.text.config(font=('courier', 9, 'normal'))
def onSave(self):
filename = asksaveasfilename()
if filename:
alltext = self.gettext()
open(filename, 'w').write(alltext)
def onCut(self):
text = self.text.get(SEL_FIRST, SEL_LAST)
self.text.delete(SEL_FIRST, SEL_LAST)
self.clipboard_clear()
self.clipboard_append(text)
def onPaste(self):
try:
text = self.selection_get(selection='CLIPBOARD')
self.text.insert(INSERT, text)
except TclError:
pass
def onFind(self):
target = askstring('SimpleEditor', 'Search String?')
if target:
where = self.text.search(target, INSERT, END)
if where:
print where
pastit = where + ('+%dc' % len(target))
self.text.tag_add(SEL, where, pastit)
self.text.mark_set(INSERT, pastit)
self.text.see(INSERT)
self.text.focus()
if len(sys.argv) > 1:
Editor(file=sys.argv[1]).mainloop()
else:
Editor().mainloop()

Your problem can be fixed by simply changing text to label. For example:
filemenu.add_command(text='Save', command=self.onSave)
should be
filemenu.add_command(label='Save', command=self.onSave)

Related

Understanding winfo_exists()

I’m trying to test the existence of a toplevel using the winfo_exists() method made available by Tkinter.
However, I cannot test the existence of a Toplevel by passing the name of this to winfo_exists() method.
I enclose a script to better clarify what I would like to do.
When you open the app, four buttons are shown. Pressing on the first appears a mask where we can, by pressing the relevant buttons, see the execution of both the winfo_exists() method and the winfo_children() method.
Selecting a Toplevel to test using the radiobox on the right happens that if the relative Toplevel is open the function work fine, otherwise generates the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/home/bc/Desktop/simple_app.py", line 113, in on_test_exist
if self.nametowidget(DICT_TOPLEVELS[self.option.get()]).winfo_exists():
File "/usr/lib/python3.7/tkinter/__init__.py", line 1353, in nametowidget
w = w.children[n]
KeyError: 'toptwo'
Do you have any suggestions?
Basically in an application with many Toplevels, how do you see if a certain Toplevel is open?
Thank you for your attention.
#!/usr/bin/python3
import sys
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
DICT_TOPLEVELS = {0:".topone",
1:".toptwo",
2:".topthree"}
class Main(ttk.Frame):
def __init__(self, parent, ):
super().__init__(name="main")
self.parent = parent
self.init_ui()
def init_ui(self):
f0 = tk.Frame(self)
bts = [("Top One", 4, self.on_open_one, "<Alt-o>"),
("Top Two", 4, self.on_open_two, "<Alt-t>"),
("Top Three", 5, self.on_open_three, "<Alt-w>"),
("Close", 0, self.parent.on_exit, "<Alt-c>")]
for btn in bts:
ttk.Button(f0,
text=btn[0],
underline=btn[1],
command = btn[2]).pack(fill=tk.X, padx=5, pady=5)
self.parent.bind(btn[3], btn[2])
f0.pack()
def on_open_one(self, evt=None):
obj = TopOne(self)
obj.on_open()
def on_open_two(self, evt=None):
obj = TopTwo(self)
obj.on_open()
def on_open_three(self, evt=None):
obj = TopThree(self)
obj.on_open()
class TopOne(tk.Toplevel):
def __init__(self, parent,):
super().__init__(name="topone")
self.parent = parent
self.minsize(200, 100)
self.voices = ('topone','toptwo','topthree')
self.option = tk.IntVar()
self.init_ui()
def init_ui(self):
f0 = tk.Frame(self, bg='SlateGray4', padx=5,pady=5)
f1 = tk.Frame(f0,)
bts = [("Call winfo_exists", 7, self.on_winfo_exists, "<Alt-c>"),
("Get winfo_children", 0, self.on_get_winfo_children, "<Alt-g>"),
("Test exist", 0, self.on_test_exist, "<Alt-t>"),
("Close", 0, self.master.on_exit, "<Alt-c>")]
for btn in bts:
ttk.Button(f1,
text=btn[0],
underline=btn[1],
command = btn[2]).pack(fill=tk.X, padx=5, pady=5)
self.parent.bind(btn[3], btn[2])
f2 = tk.Frame(f0,)
ttk.Label(f2, text="Toplevels:").pack()
for index, text in enumerate(self.voices):
ttk.Radiobutton(f2,
text=text,
variable=self.option,
value=index,).pack()
f0.pack(fill=tk.BOTH, expand=1, padx=5, pady=5)
f2.pack(side=tk.RIGHT, fill=tk.Y, padx=5, pady=5, expand=0)
f1.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5, expand=0)
def on_open(self):
msg = "{0}".format(self.winfo_name().title())
self.title(msg)
def on_winfo_exists(self, evt=None):
for obj in self.nametowidget(".").winfo_children():
if self.nametowidget(obj).winfo_exists():
print("{0} is exist!".format(self.nametowidget(obj).winfo_name()))
def on_get_winfo_children(self, evt=None):
for obj in self.nametowidget(".").winfo_children():
print(self.master.nametowidget(obj))
def on_test_exist(self):
print("You have selected to test if {0} Toplevel exist.".format(DICT_TOPLEVELS[self.option.get()]),)
if self.nametowidget(DICT_TOPLEVELS[self.option.get()]).winfo_exists():
print("Well Toplevel named {0} exists!".format(self.nametowidget(DICT_TOPLEVELS[self.option.get()]).winfo_name()))
else:
print("I’m sorry but Toplevel named {0} doesn’t exist!".format(DICT_TOPLEVELS[self.option.get()]))
class TopTwo(tk.Toplevel):
def __init__(self, parent,):
super().__init__(name="toptwo")
self.parent = parent
self.minsize(200, 100)
self.init_ui()
def init_ui(self):
f = tk.Frame(self, bg='DarkSeaGreen4', padx=5,pady=5)
f.pack(fill=tk.BOTH, expand=1, padx=5, pady=5)
def on_open(self):
msg = "{0}".format(self.winfo_name().title())
self.title(msg)
class TopThree(tk.Toplevel):
def __init__(self, parent,):
super().__init__(name="topthree")
self.parent = parent
self.minsize(200, 100)
self.init_ui()
def init_ui(self):
f = tk.Frame(self, bg='DarkSeaGreen3', padx=5,pady=5)
f.pack(fill=tk.BOTH, expand=1, padx=5, pady=5)
def on_open(self):
msg = "{0}".format(self.winfo_name().title())
self.title(msg)
class App(tk.Tk):
"""Main Application start here"""
def __init__(self,):
super().__init__()
self.protocol("WM_DELETE_WINDOW", self.on_exit)
#self.resizable(width=False, height=False)
self.geometry('400x200')
self.title("Simple App")
Main(self).pack(fill=tk.BOTH, expand=1)
def on_exit(self):
msg = "Do you want to quit?"
if messagebox.askokcancel(self.title(), msg, parent=self):
self.destroy()
def main():
app = App()
app.mainloop()
if __name__ == '__main__':
main()

Adding line numbers to text widget using Tkinter

I have text box my_text on gui at location
my_text = Text(root, width=98, height=35, font=("Helvetica", 10), bg="cyan", fg="black")
my_text.grid(row=4, column=0, padx=(20, 50), pady=(20, 0), rowspan=3, sticky="e")
I want to add lines numbers to this text box using Bryan Oakley code here.
My code:
import tkinter as tk
from tkinter import *
root = Tk()
my_text = Text(root, width=98, height=35, font=("Helvetica", 10), bg="cyan", fg="black")
my_text.grid(row=4, column=0, padx=(20, 50), pady=(20, 0), rowspan=3, sticky="e")
text_file = open("sample.xml", 'r')
s = text_file.read()
my_text.delete("1.0", "end")
my_text.insert(END, s)
class TextLineNumbers(tk.Canvas):
def __init__(self, *args, **kwargs):
tk.Canvas.__init__(self, *args, **kwargs)
self.root = Tk()
self.textwidget = None
def attach(self, text_widget):
self.textwidget = text_widget
def redraw(self, *args):
'''redraw line numbers'''
self.delete("all")
i = self.textwidget.index("#0,0")
while True :
dline= self.textwidget.dlineinfo(i)
if dline is None: break
y = dline[1]
linenum = str(i).split(".")[0]
self.create_text(2,y,anchor="nw", text=linenum)
i = self.textwidget.index("%s+1line" % i)
def run(self):
self.root.mainloop()
linenos = TextLineNumbers()
linenos.attach(my_text)
linenos.redraw()
root.mainloop()
Code is not displaying line number. It is displaying just text. How to display linenumbers in text box? Thanks in advance.
You mentioned this great example, why not just modify it to suit your needs? I was curious and modified the Example class from given link by adding a button to call a function load_xml which loads files via filechooser, deletes the previous data in the CustomText widget and inserts the new data:
import tkinter as tk
from tkinter import filedialog
import os
class TextLineNumbers(tk.Canvas):
def __init__(self, *args, **kwargs):
tk.Canvas.__init__(self, *args, **kwargs)
self.textwidget = None
def attach(self, text_widget):
self.textwidget = text_widget
def redraw(self, *args):
'''redraw line numbers'''
self.delete("all")
i = self.textwidget.index("#0,0")
while True:
dline = self.textwidget.dlineinfo(i)
if dline is None:
break
y = dline[1]
linenum = str(i).split(".")[0]
self.create_text(2, y, anchor="nw", text=linenum)
i = self.textwidget.index("%s+1line" % i)
class CustomText(tk.Text):
def __init__(self, *args, **kwargs):
tk.Text.__init__(self, *args, **kwargs)
# create a proxy for the underlying widget
self._orig = self._w + "_orig"
self.tk.call("rename", self._w, self._orig)
self.tk.createcommand(self._w, self._proxy)
def _proxy(self, *args):
# let the actual widget perform the requested action
cmd = (self._orig,) + args
result = self.tk.call(cmd)
# generate an event if something was added or deleted,
# or the cursor position changed
if (args[0] in ("insert", "replace", "delete") or
args[0:3] == ("mark", "set", "insert") or
args[0:2] == ("xview", "moveto") or
args[0:2] == ("xview", "scroll") or
args[0:2] == ("yview", "moveto") or
args[0:2] == ("yview", "scroll")):
self.event_generate("<<Change>>", when="tail")
# return what the actual widget returned
return result
class Example(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.text = CustomText(self)
self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
self.text.configure(yscrollcommand=self.vsb.set)
self.text.tag_configure("bigfont", font=("Helvetica", "24", "bold"))
self.linenumbers = TextLineNumbers(self, width=30)
self.linenumbers.attach(self.text)
self.vsb.pack(side="right", fill="y")
self.linenumbers.pack(side="left", fill="y")
self.text.pack(side="right", fill="both", expand=True)
# new button to call load_xml and show status
self.load_button = tk.Button(root, text="Load file", command=self.load_xml)
self.load_button.pack(side="top")
self.text.bind("<<Change>>", self._on_change)
self.text.bind("<Configure>", self._on_change)
self.text.insert("end", "one\ntwo\nthree\n")
self.text.insert("end", "four\n", ("bigfont",))
self.text.insert("end", "five\n")
def _on_change(self, event):
self.linenumbers.redraw()
def load_xml(self):
"""Load any file, delete current text and insert new data"""
input_file = filedialog.askopenfilename(title="Load a textfile",
filetypes=(("XML", "*.xml"),
("Text", "*.txt"),
("All files", "*.*")),
initialdir=os.getcwd())
if input_file:
self.text.delete("1.0", "end")
self.load_button.config(text=f"Currently loaded: {input_file.split(os.sep)[-1]}")
with open(input_file, 'r') as f:
self.text.insert("end", f.read())
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()

how to output plain text in an output box in tkinter

i have written the "instruction" for my tkinter program on a .txt file and when the Instruction button is pressed, I would like a separate window to be created with the instruction copied from the text file into the output box.
I would be very grateful if anyone could help me.
this is what I have done so far but it doesn't work at all.
instructionBtn = Button(window, text="?", command=start, height = 5, width =30,fg="black", bg="lime green", font=("Comic Sans MS", 10))
instructionBtn.grid(row=29, column=1, sticky=S)
window.mainloop()
def instruction():
instructionwindow = Tk() #create window
instructionwindow.geometry("500x350")
instructionwindow.title("Instruction")
instructionwindow.configure(background='white')
instructionFile=open("Instruction.txt","r")
instruction.read
textboxOutput = Text(window, wrap="Instruction.txt", width = 150, height = 20)
textboxOutput.grid(row = 20, column = 0, columnspan=10)
instruction.mainloop()
When I want a second window, often a message box will do the trick, like so:
from Tkinter import *
from tkMessageBox import showinfo
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
self.instr = Button(frame, text="Instruction", command=self.instruction)
self.instr.pack(side=LEFT)
def instruction(self):
try:
with open("instruction.txt") as fp:
message = fp.read()
except IOError:
message = 'No instructions available'
showinfo("Instructions", message)
root = Tk()
app = App(root)
root.mainloop()
Or, if you prefer an OOP style:
# template: https://stackoverflow.com/a/17470842/8747
# Use Tkinter for python 2, tkinter for python 3
import Tkinter as tk
import tkMessageBox
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.button = tk.Button(
self, text="QUIT", fg="red", command=self.quit)
self.instr = tk.Button(
self, text="Instruction", command=self.instruction)
self.button.pack(side=tk.LEFT)
self.instr.pack(side=tk.LEFT)
def instruction(self):
try:
with open("instruction.txt") as fp:
message = fp.read()
except IOError:
message = 'No instruction available'
msg = tkMessageBox.showinfo("Instruction", message)
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()
Of course, sometimes a message box isn't flexible enough, and you need to create a top-level window:
# template: https://stackoverflow.com/a/17470842/8747
# Use Tkinter for python 2, tkinter for python 3
import Tkinter as tk
import tkMessageBox
class Instruction(tk.Toplevel):
def __init__(self, parent, message, *args, **kwargs):
tk.Toplevel.__init__(self, parent, *args, **kwargs)
self.msg = tk.Message(self, text=message)
self.button = tk.Button(self, text="Dismiss", command=self.destroy)
self.msg.pack()
self.button.pack()
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.button = tk.Button(
self, text="QUIT", fg="red", command=self.quit)
self.instr = tk.Button(
self, text="Instruction", command=self.instruction)
self.button.pack(side=tk.LEFT)
self.instr.pack(side=tk.LEFT)
def instruction(self):
try:
with open("instruction.txt") as fp:
message = fp.read()
except IOError:
message = 'No instruction available'
msg = Instruction(self, message)
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()

How to change __init__ to Tk() windows?

Can anyone help me to understand the window code? Im trying to make all the objects run in a Toplevel() function instead of a new instance of Tkinter because that doesn't work launching it from another program. Theres no window = Tk() function anywhere just init and frame.
from tkinter import *
from tkinter.simpledialog import askstring
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import askokcancel
def text_edit() :
class Quitter(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.pack()
widget = Button(self, text='Quit', command=self.quit)
widget.pack(expand=YES, fill=BOTH, side=LEFT)
def quit(self):
ans = askokcancel('Verify exit', "Really quit?")
if ans: Frame.quit(self)
class ScrolledText(Frame):
def __init__(self, parent=None, text='', file=None):
Frame.__init__(self, parent)
self.pack(expand=YES, fill=BOTH)
self.makewidgets()
self.settext(text, file)
def makewidgets(self):
sbar = Scrollbar(self)
text = Text(self, relief=SUNKEN)
sbar.config(command=text.yview)
text.config(yscrollcommand=sbar.set)
sbar.pack(side=RIGHT, fill=Y)
text.pack(side=LEFT, expand=YES, fill=BOTH)
self.text = text
def settext(self, text='', file=None):
if file:
text = open(file, 'r').read()
self.text.delete('1.0', END)
self.text.insert('1.0', text)
self.text.mark_set(INSERT, '1.0')
self.text.focus()
def gettext(self):
return self.text.get('1.0', END+'-1c')
class SimpleEditor(ScrolledText):
def __init__(self, parent=None, file=None):
frm = Frame(parent)
frm.pack(fill=X)
Button(frm, text='Save', command=self.onSave).pack(side=LEFT)
Button(frm, text='Cut', command=self.onCut).pack(side=LEFT)
Button(frm, text='Paste', command=self.onPaste).pack(side=LEFT)
Button(frm, text='Find', command=self.onFind).pack(side=LEFT)
Quitter(frm).pack(side=LEFT)
ScrolledText.__init__(self, parent, file=file)
self.text.config(font=('courier', 9, 'normal'))
def onSave(self):
filename = asksaveasfilename()
if filename:
alltext = self.gettext()
open(filename, 'w').write(alltext)
def onCut(self):
text = self.text.get(SEL_FIRST, SEL_LAST)
self.text.delete(SEL_FIRST, SEL_LAST)
self.clipboard_clear()
self.clipboard_append(text)
def onPaste(self):
try:
text = self.selection_get(selection='CLIPBOARD')
self.text.insert(INSERT, text)
except TclError:
pass
def onFind(self):
target = askstring('SimpleEditor', 'Search String?')
if target:
where = self.text.search(target, INSERT, END)
if where:
print (where)
pastit = where + ('+%dc' % len(target))
#self.text.tag_remove(SEL, '1.0', END)
self.text.tag_add(SEL, where, pastit)
self.text.mark_set(INSERT, pastit)
self.text.see(INSERT)
self.text.focus()
if __name__ == '__main__':
try:
SimpleEditor(file=sys.argv[1]).mainloop()
except IndexError:
SimpleEditor().mainloop()
You have to adapt to Tkinter as it was written to be used (or write your own which is beyond me), instead of trying to pound it into some preconceived form.
try:
import Tkinter as tk ## Python 2.x
except ImportError:
import tkinter as tk ## Python 3.x
from functools import partial
class OpenToplevels():
""" open and close additional Toplevels with a button
"""
def __init__(self):
self.root = tk.Tk()
self.button_ctr=0
but=tk.Button(self.root, text="Open a Toplevel",
command=self.open_another)
but.grid(row=0, column=0)
tk.Button(self.root, text="Exit Tkinter", bg="red",
command=self.root.quit).grid(row=1, column=0, sticky="we")
self.root.mainloop()
def close_it(self, id):
id.destroy()
def open_another(self):
self.button_ctr += 1
id = tk.Toplevel(self.root)
id.title("Toplevel #%d" % (self.button_ctr))
tk.Button(id, text="Close Toplevel #%d" % (self.button_ctr),
command=partial(self.close_it, id),
bg="orange").grid(row=1, column=0)
Ot=OpenToplevels()

Deleting text from an edit control in Python 2.7?

How can I program the example below to delete all contents from the Edit box? (this is example is taken from http://www.java2s.com/Code/Python/GUI-Tk/SimpleEditor.htm)
My guess is that one must select all the contents and then do some sort of .tag_remove(SEL, '1.0', END) but I can't find the commands to program it to select all the text.
from Tkinter import *
from tkSimpleDialog import askstring
from tkFileDialog import asksaveasfilename
from tkMessageBox import askokcancel
class Quitter(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.pack()
widget = Button(self, text='Quit', command=self.quit)
widget.pack(expand=YES, fill=BOTH, side=LEFT)
def quit(self):
ans = askokcancel('Verify exit', "Really quit?")
if ans: Frame.quit(self)
class ScrolledText(Frame):
def __init__(self, parent=None, text='', file=None):
Frame.__init__(self, parent)
self.pack(expand=YES, fill=BOTH)
self.makewidgets()
self.settext(text, file)
def makewidgets(self):
sbar = Scrollbar(self)
text = Text(self, relief=SUNKEN)
sbar.config(command=text.yview)
text.config(yscrollcommand=sbar.set)
sbar.pack(side=RIGHT, fill=Y)
text.pack(side=LEFT, expand=YES, fill=BOTH)
self.text = text
def settext(self, text='', file=None):
if file:
text = open(file, 'r').read()
self.text.delete('1.0', END)
self.text.insert('1.0', text)
self.text.mark_set(INSERT, '1.0')
self.text.focus()
def gettext(self):
return self.text.get('1.0', END+'-1c')
class SimpleEditor(ScrolledText):
def __init__(self, parent=None, file=None):
frm = Frame(parent)
frm.pack(fill=X)
Button(frm, text='Save', command=self.onSave).pack(side=LEFT)
Button(frm, text='Cut', command=self.onCut).pack(side=LEFT)
Button(frm, text='Paste', command=self.onPaste).pack(side=LEFT)
Button(frm, text='Find', command=self.onFind).pack(side=LEFT)
Quitter(frm).pack(side=LEFT)
ScrolledText.__init__(self, parent, file=file)
self.text.config(font=('courier', 9, 'normal'))
def onSave(self):
filename = asksaveasfilename()
if filename:
alltext = self.gettext()
open(filename, 'w').write(alltext)
def onCut(self):
text = self.text.get(SEL_FIRST, SEL_LAST)
self.text.delete(SEL_FIRST, SEL_LAST)
self.clipboard_clear()
self.clipboard_append(text)
def onPaste(self):
try:
text = self.selection_get(selection='CLIPBOARD')
self.text.insert(INSERT, text)
except TclError:
pass
def onFind(self):
target = askstring('SimpleEditor', 'Search String?')
if target:
where = self.text.search(target, INSERT, END)
if where:
print where
pastit = where + ('+%dc' % len(target))
#self.text.tag_remove(SEL, '1.0', END)
self.text.tag_add(SEL, where, pastit)
self.text.mark_set(INSERT, pastit)
self.text.see(INSERT)
self.text.focus()
if __name__ == '__main__':
try:
SimpleEditor(file=sys.argv[1]).mainloop()
except IndexError:
SimpleEditor().mainloop()
The text widget has a delete method, which you can use to delete characters. You don't need to select the characters first.
If you want to delete all of the text, just do:
self.text.delete("1.0", "end")
(you can also use a tkinter constant instead of the string "end", but I don't see the point)

Categories

Resources