【问题标题】:How to make methods of Tkinter's class private?如何将 Tkinter 类的方法设为私有?
【发布时间】:2022-06-11 03:18:29
【问题描述】:

这是一个窗口的代码,使用tkinter 库和OOP。我想将App 类的方法设为私有。但是其中一些,比如下面代码中的方法destroy应该是公开的

from tkinter import *
from tkinter import ttk

class App(Tk):
    def __init__(self):
        super().__init__()

        # window settings
        root.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()

【问题讨论】:

  • 你不能,至少在不违反里氏替换原则的情况下不能。作为Tk 的实例(通过子类App),必须假定root 具有title 方法。

标签: python python-3.x class oop tkinter


【解决方案1】:

如果您想要不公开一个或多个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,但顾名思义,您需要对由此产生的任何错误负责)您需要编写的样板数量以公开您确实想要访问的方法。 (减少样板文件超出了此答案的范围。)

【讨论】:

    猜你喜欢
    • 2010-10-01
    • 2011-01-23
    • 2010-11-25
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    相关资源
    最近更新 更多