将小部件子类化以创建自定义小部件是很正常的。但是,如果此自定义小部件由多个小部件组成,您通常会将Frame
. 例如,要创建一个带有滚动条的文本小部件,我会这样做:
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()
使用这种方法,请注意在插入文本时需要如何引用内部文本小部件。如果您希望这个小部件看起来更像一个真正的文本小部件,您可以创建到部分或全部文本小部件功能的映射。例如:
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()