एक कस्टम बनाने के लिए विजेट को उप-वर्ग करना बहुत सामान्य है। हालांकि, यदि यह कस्टम विजेट एक से अधिक विजेट से बना है, तो आप आमतौर पर Frame
उपclass करेंगे। उदाहरण के लिए, एक विजेट एक स्क्रॉलबार मैं कुछ इस तरह करना होगा के साथ एक पाठ विजेट है कि बनाने के लिए:
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()
क्या मैं पूछने के लिए कोशिश कर रहा हूँ है, यह Tkinter.Text (या किसी अन्य विजेट यह तरीकों और कार्यों है बनाए रखने के लिए) एक कस्टम विजेट बनाने के लिए उपवर्ग के लिए एक अच्छा अभ्यास है। इस मामले में मैं Tkinter.Text subclassing हूँ, इसे मेरी कक्षा के भीतर एक फ्रेम पर एक स्क्रॉलबार के साथ रखकर। या मुझे फ्रेम को उप-वर्ग करना चाहिए और टेक्स्ट विजेट और स्क्रॉलबार को सीधे उस पर रखना चाहिए और अपनी खुद की विधियों और कार्यों को बनाना चाहिए? – user2830098
मेरे उत्तर का अपडेट देखें –