【问题标题】:Are Widgets Classes or Methods in Tkinter?Tkinter 中的小部件类或方法是什么?
【发布时间】:2020-09-12 19:18:22
【问题描述】:

使用Text() 方法创建一个文本小部件。

import tkinter as tk 
root = tk.Tk()
T = tk.Text(root, height=2, width=30) 
T.pack() 
T.insert(tk.END, "Just a text Widget\nin two lines\n") 
w = tk.Label(root, text="Hello Tkinter!") 
w.pack() 
root.mainloop()

我是 Python 新手。我的理解是TextLabel 是类,Tw 是从TextLabel 类创建的对象。但是在上面的文本示例中,一个网站提到了

使用Text() 方法创建文本小部件。

我现在完全糊涂了。 pack() 是一种方法,我们可以将方法应用于我们从 LabelText 等类创建的对象(此处为 Tw)。

如果LabelTextButton 等小部件是类或方法,请告诉我。

【问题讨论】:

    标签: python python-3.x python-2.7 tkinter widget


    【解决方案1】:

    Tkinter 小部件是类。

    但是在上面的文本示例中,一个网站提到使用 Text() 方法创建了一个文本小部件。

    那个网站不正确。它们是类,您可以通过查看 tkinter 的源代码来验证这一点,您将在其中看到每个小部件的类定义(TextLabelFrame 等)。

    例如,文本小部件的第一部分如下所示(取自 tkinter 的 __init__.py 文件):

    class Text(Widget, XView, YView):
        """Text widget which can display text in various forms."""
        def __init__(self, master=None, cnf={}, **kw):
            """Construct a text widget with the parent MASTER.
    
            STANDARD OPTIONS
    
                background, borderwidth, cursor,
                exportselection, font, foreground,
                highlightbackground, highlightcolor,
                highlightthickness, insertbackground,
                insertborderwidth, insertofftime,
                insertontime, insertwidth, padx, pady,
                relief, selectbackground,
                selectborderwidth, selectforeground,
                setgrid, takefocus,
                xscrollcommand, yscrollcommand,
    
            WIDGET-SPECIFIC OPTIONS
    
                autoseparators, height, maxundo,
                spacing1, spacing2, spacing3,
                state, tabs, undo, width, wrap,
    
            """
            Widget.__init__(self, master, 'text', cnf, kw)
    

    【讨论】:

      【解决方案2】:

      inspect 模块可能会帮助您消除困惑。

      In [37]: import inspect
      
      In [38]: from tkinter import Text
      
      In [39]: T = Text()
      
      In [40]: inspect.isclass(Text)
      Out[40]: True
      
      In [41]: inspect.ismethod(Text)
      Out[41]: False
      
      In [42]: inspect.ismethod(T.pack)
      Out[42]: True
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-14
        • 2017-08-27
        • 1970-01-01
        • 1970-01-01
        • 2013-05-31
        相关资源
        最近更新 更多