tkinter這是使用庫和 OOP的視窗代碼。我想將類的方法設為App私有。但是其中一些,比如destroy下面代碼中的方法應該是公開的
from tkinter import *
from tkinter import ttk
class App(Tk):
def __init__(self):
super().__init__()
# window settings
self.title("Private Attributes")
self.resizable(width=False, height=False)
root = App() # create window
root.title("Public Attributes") # this shouldn't work
ttk.Label(root, text="Close this window").pack()
ttk.Button(root, text="Close", command=root.destroy).pack() # this should work
root.mainloop()
uj5u.com熱心網友回復:
如果你想要一些不公開一個或多個Tk方法的東西,你應該使用組合而不是繼承。例如,
class App:
def __init__(self):
self._root = Tk()
self._root.title("Private Attributes")
self._root.resizable(width=False, height=True)
def mainloop(self):
return self._root.mainloop()
root = App()
root.title("Public Attributes") # AttributeError
root.mainloop() # OK
您需要確定限制對各種Tk方法的訪問的能力(請記住,您仍然可以self._root直接訪問,但顧名思義,您需要對由此產生的任何錯誤負責)超過您需要的樣板數量寫入以公開您確實想要訪問的方法。(減少樣板檔案超出了此答案的范圍。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/489516.html
標籤:Python python-3.x 班级 哎呀 tkinter
