È molto normale creare una sottoclasse di un widget per crearne uno personalizzato. Tuttavia, se questo widget personalizzato è composto da più di un widget, normalmente sottoclassi Frame
. Ad esempio, per creare un widget che è un widget di testo con una barra di scorrimento che vorrei fare qualcosa di simile:
import Tkinter as tk
class ScrolledText(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent)
self.text = tk.Text(self, *args, **kwargs)
self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
self.text.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(side="right", fill="y")
self.text.pack(side="left", fill="both", expand=True)
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.scrolled_text = ScrolledText(self)
self.scrolled_text.pack(side="top", fill="both", expand=True)
with open(__file__, "r") as f:
self.scrolled_text.text.insert("1.0", f.read())
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
Con questo approccio, nota come è necessario fare riferimento al widget di testo interno durante l'inserimento del testo. Se si desidera che questo widget assomigli più ad un widget di testo reale, è possibile creare una mappatura per alcune o tutte le funzioni del widget di testo. Ad esempio:
import Tkinter as tk
class ScrolledText(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent)
self.text = tk.Text(self, *args, **kwargs)
self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
self.text.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(side="right", fill="y")
self.text.pack(side="left", fill="both", expand=True)
# expose some text methods as methods on this object
self.insert = self.text.insert
self.delete = self.text.delete
self.mark_set = self.text.mark_set
self.get = self.text.get
self.index = self.text.index
self.search = self.text.search
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.scrolled_text = ScrolledText(self)
self.scrolled_text.pack(side="top", fill="both", expand=True)
with open(__file__, "r") as f:
self.scrolled_text.insert("1.0", f.read())
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
Quello che sto cercando di chiedere è, è una buona pratica sottoclasse il Tkinter.Text (o qualsiasi altro widget per mantenere i suoi metodi e funzioni) per creare un widget personalizzato. In questo caso sto sottoclassi Tkinter.Text, posizionandolo con una barra di scorrimento su un frame all'interno della mia classe. O dovrei creare una sottoclasse di Frame e posizionare il Text Widget e la barra di scorrimento direttamente su di esso e creare i miei metodi e le mie funzioni? – user2830098
Vedere l'aggiornamento della mia risposta –