Reputation: 1372
Okay, i've been trying to create a small text editor in Tkinter. I've stubble across a problem and I can't seem to find the answer. If anyone could just help me, I'd be very happy.
First of all, here is my code :
import tkinter as tk
import tkinter.filedialog as tkfile
class PyTedi(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
# Instantiate Menu
main_menu = tk.Menu(self)
menu_bar = PyTediMenu(main_menu)
main_menu.add_cascade(label='File', menu=menu_bar)
self.config(menu=main_menu)
# Instantiate Text Area
text_area = PyTediTextArea(self)
text_area.pack(side=tk.BOTTOM)
# Instantiate Tool Bar
tool_bar = PyTediToolBar(self)
tool_bar.pack(side=tk.TOP)
class PyTediMenu(tk.Menu):
def __init__(self, parent):
tk.Menu.__init__(self, parent)
self.add_command(label='New', command=None)
self.add_command(label='Open', command=None)
self.add_command(label='Save', command=tkfile.asksaveasfile)
self.add_separator()
self.add_command(label='Exit', command=self.quit)
class PyTediToolBar(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, height=30)
class PyTediTextArea(tk.Text):
def __init__(self, parent):
tk.Text.__init__(self, parent)
if __name__ == '__main__':
app = PyTedi()
app.mainloop()
Basically, I've found out, (From another stack question) That it is a good idea to create class based components... My problem is, let's say I want to create a command -> Save File. So I create a method inside my Menu and link to the save function. BUT, how do I grab the text area content and write it to a file ? They are not even part of the same class. Is it a bad design implementation or it's just me ? Thanks !
Upvotes: 0
Views: 989
Reputation: 5933
while it is a good idea to use class based programming, i would like to point out that unless you are modifying the widget in some way, subclassing it is completely unnecessary, when you create the class PyTediTextArea
you aren't actually modifying the original text class in any way, so it would be simpler for you to simply change
text_area = PyTediTextArea(self)
to
self.text_area = tk.Text(self)
that way you save yourself subclassing at the bottom and from anywhere in your main class you can simply call
self.text_area.get(0, "end")
to get all of the text in the widget
James
Upvotes: 1