위젯을 서브 클래 싱하여 맞춤형을 만드는 것은 매우 정상입니다. 그러나이 사용자 정의 위젯이 두 개 이상의 위젯으로 구성되는 경우 일반적으로 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()
나는 사용자 정의 위젯을 만들기 위해 Tkinter.Text (또는 다른 위젯이 메소드와 함수를 유지하도록) 하위 클래스를 만드는 것이 좋습니다. 이 경우 Tkinter.Text를 하위 클래스 화하여 클래스의 프레임에 스크롤바를 배치합니다. 아니면 프레임 하위 클래스 및 텍스트 위젯 및 스크롤 막대를 직접 배치하고 내 자신의 메서드 및 함수를 만들어야합니까? – user2830098
내 대답의 업데이트보기 –