我目前正在开发一个程序,该程序可以处理Python程序中许多不同的可能的输入小部件。

我需要一些代码来确定特定对象是哪种小部件类型,例如EntryCheckbutton

我尝试使用type(var)方法以及self都无济于事(我收到了缺少必需变量var.__class__的错误),但没有任何进展。

for d in dataTypes:
    if isinstance(d, Entry):
        print("Found Entry!")
    elif type(d).__name__ == 'Checkbutton':
        print("Found Checkbox!")


有谁知道如何解决这个问题?

最佳答案

如果需要名称作为字符串,则可以使用.winfo_class()方法:

for d in dataTypes:
    if d.winfo_class() == 'Entry':
        print("Found Entry!")
    elif d.winfo_class() == 'Checkbutton':
        print("Found Checkbutton!")


或者,您可以访问__name__属性:

for d in dataTypes:
    if d.__name__ == 'Entry':
        print("Found Entry!")
    elif d.__name__ == 'Checkbutton':
        print("Found Checkbutton!")


也就是说,使用isinstance是更常见的/ pythonic方法:

for d in dataTypes:
    if isinstance(d, Entry):
        print("Found Entry!")
    elif isinstance(d, Checkbutton):
        print("Found Checkbutton!")


另外,您当前的代码失败,因为type(d).__name__不会返回您认为的结果:

>>> from tkinter import Checkbutton
>>> type(Checkbutton).__name__
'type'
>>>


请注意,它返回type返回的类型对象的名称,而不是Checkbutton的名称。

关于python - 获取Python Tkinter对象类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27281097/

10-12 07:40
查看更多